Project

General

Profile

Actions

Bug #6547

closed

DateTime.new does not call #initialize

Added by lmc (Luke Mcildoon) almost 12 years ago. Updated almost 12 years ago.

Status:
Rejected
Target version:
-
ruby -v:
ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux]
Backport:
[ruby-core:45427]

Description

Classes that extend DateTime don't appear to have their "initialize" instance method called from "new".

To reproduce:
irb(main):001:0> [RUBY_VERSION,RUBY_PLATFORM]
=> ["1.9.3", "i686-linux"]
irb(main):002:0> require "date"
=> true
irb(main):003:0> class DateTimeExtension < DateTime
irb(main):004:1> def initialize(*args)
irb(main):005:2> raise "DateTimeExtension#initialize called"
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> DateTimeExtension.new
=> #<DateTimeExtension: -4712-01-01T00:00:00+00:00 ((0j,0s,0n),+0s,2299161j)> # no exception raised

I expected calling "DateTimeExtension.new" to raise the exception from inside "initialize".


Files

date_initialize_patch.diff (1.96 KB) date_initialize_patch.diff unified diff of changes to date_core.c lmc (Luke Mcildoon), 06/27/2012 05:25 PM

Updated by nobu (Nobuyoshi Nakada) almost 12 years ago

  • Category set to ext
  • Status changed from Open to Assigned
  • Assignee set to tadf (tadayoshi funaba)
  • Priority changed from Normal to 3

=begin
It's a standard behavior of (({Class.new})) to allocate an instance and call
initialize method on it, but (({DateTime.new})) overrides it. This is the
old habit before ruby 1.8.

Although I'm uncertain why you need it, if you really need a class to
represent arbitrary time but don't need precise historical time, you
can use (({Time})) also, instead of (({DateTime})).
=end

Updated by tadf (tadayoshi funaba) almost 12 years ago

  • Status changed from Assigned to Rejected

i believe this is not a bug.
it's expensive/slow to call initialize.
on DateTime, new is one of various constractors.
if you want to write a subclass of DateTime, you may rewrite each of them.

Updated by lmc (Luke Mcildoon) almost 12 years ago

I disagree, I believe this is a bug since it results in extremely surprising behaviour, and no other stdlib classes do this (even String.new calls initialize).
I've fixed this myself by adding calls to rb_obj_call_init in date_core.c, and benchmarked it over 1,000,000 calls.

Without initialize: 0.51281475 sec
With initialize: 0.84253075 sec

While I agree there is a performance decrease, I think that the current behaviour is arguably "cheating", especially considering core classes that are used far more often than Date/DateTime behave correctly.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0