.

On Fri, Sep 18, 2009 at 1:15 PM, luisealvarezb
<luisealvarezb / hotmail.com> wrote:
>
> Hi, everybody:
>
> I have been tring to derive a class from DateTime and in doing so have
> come across some nasty problems: it turns out overriding the
> constructor is not straight forward at all. I was looking for some
> pointers, anyone????
> Here is what I have:
>
> require 'rubygems'
> #~ require 'ruby-debug'
>
> require 'date'
> class Event < DateTime
> class << self
> alias :old_new :new
> def new summary, due_date, long_text='', alarm_time=0
> dt = DateTime.parse( due_date )
> obj = old_new(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec,
> dt.sg)
> obj.send :initialize, summary, long_text, alarm_time
> obj
> end
> end
>
> attr_accessor :summary, :long_text, :alarm_time
>
> def initialize summary, long_text='', alarm_time=0
> @summary = summary
> @long_text = long_text
> @alarm_time = alarm_time
> end
> end
>
> e = Event.new "something to do", "2009-10-10T00:00"
> puts e.summary
> puts e.year
>
> e is an event at the end of the code, it has a summary and what ever
> else I pass in but the DateTime structures are not initialized
> correctly. In other words e.year gives me an error and here it is:
>
> /usr/lib/ruby/1.8/date.rb:492:in `ajd_to_jd': undefined method `+' for
> nil:NilClass (NoMethodError)
> from /usr/lib/ruby/1.8/date.rb:1051:in `__21105__'
> from (eval):4:in `jd'
> from /usr/lib/ruby/1.8/date.rb:1066:in `__21521__'
> from (eval):4:in `civil'
> from /usr/lib/ruby/1.8/date.rb:1081:in `year'
> from D:/workspace/todo/lib/tester.rb:29
>
> I have tryed some other variants of the code as well and it gets even
> worse. Can any one help, please?

It looks to me that this is a case where you might be better served by using
composition and delegation rather than inheritance: instead of an Event
being a specialized DateTime, it would have a DateTime instance as an
instance variable and delegate certain methods (e.g., year, etc.) to that
instance variable.