I'd like to subclass NilClass, creating a NullCase, implementing in Ruby a simple example of Martin F.'s "SpecialCase" pattern ( http://patternshare.org/default.aspx/Home.MF.SpecialCase ) I'd like to subclass NilClass, so that the object returns false (and nil? returns true). But, I'd like to override method_missing so that it returns the an instance of NullCase - not an exception, and not a regular nil. I had trouble subclassing NilClass - there's no new method - how do I do this? Basically, usage would be like def a_method ... if condition x else NULL_CASE end end Later, you could do: a = o.a_method a.address.zip #--> No errors, just nil's instead of if a && a.address && a.address.zip a.address.zip else nil end Please cc all responses to me at listrecv at gmail, thanks!
on 2005-11-14 00:59
on 2005-11-14 01:20
On 11/13/05, firstname.lastname@example.org <email@example.com> wrote: > I had trouble subclassing NilClass - there's no new method - how do I > do this? You don't. See the thread beginning with [ruby-talk:157101]. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...
on 2005-11-14 03:17
On Nov 13, 2005, at 5:57 PM, firstname.lastname@example.org wrote: > Later, you could do: > a = o.a_method > a.address.zip #--> No errors, just nil's > > instead of > if a && a.address && a.address.zip > a.address.zip > else > nil > end Take a look at the NullObject pattern: http://c2.com/cgi/wiki?NullObject you might be able to come up with some specific null objects for your scenario. I'd shoot for something specific to you problem but Ruby of course will let you create a "generic" null object: class Object def mynull? false end end class MyNull def method_missing(name, *args, &block) self end def mynull? true end def to_s "" end end You can't depend on the object testing as false, use #mynull? if you need to know what it is. Gary W.