Forum: Ruby Subclassing NilClass

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ccfe7d097475a32dc3ff78d6fc42c852?d=identicon&s=25 listrecv (Guest)
on 2005-11-13 23:59
(Received via mailing list)
I'd like to subclass NilClass, creating a NullCase, implementing in
Ruby a simple example of Martin Fowler'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!
Eba32a4bc6f1a4f60b434b7cae0715de?d=identicon&s=25 rascal1182 (Guest)
on 2005-11-14 00:20
(Received via mailing list)
On 11/13/05, listrecv@gmail.com <listrecv@gmail.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/...
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 gwtmp01 (Guest)
on 2005-11-14 02:17
(Received via mailing list)
On Nov 13, 2005, at 5:57 PM, listrecv@gmail.com 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 Wright
This topic is locked and can not be replied to.