I just want to use Null Object Design Pattern, but I found I can inherit from NilClass.
I can write a method \"nil?\" and return false but what if user write code be
Instead of inheriting from NilClass
I do the following
class NullObject < BasicObject
include ::Singleton
def method_missing(method, *args, &block)
if nil.respond_to? method
nil.send method, *args, &block
else
self
end
end
end
This gives you any custom method that have been monkey patched onto NilClass
(such as ActiveSupport's blank?
and nil?
). You can also of course add custom null object behaviors, or change method_missing
to handle other calls differently (this one returns the NullObject for chaining, but you could return nil
for example).