Subclassing NilClass

L

listrecv

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!
 
G

gwtmp01

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top