Null Objects
August 2007 • Daniel Lucraft
Tom Locke and I have similar proclivities. He says:
class Object
def _?()
self
end
end
class NilClass
def _?()
SafeNil.new
end
end
class SafeNil
def method_missing(*args, &b)
nil.send(*args, &b) rescue nil
end
end
I say:
class Object
def null
n = nil
def n.method_missing(*args)
null
end
n
end
end
The difference:
string_or_nil._?.length # Tom's
(string_or_nil||null).length # mine
I like being able to go more than one method deep,
(string_or_nil||null).length * 4
But that might not be to your taste.