Skip to content

Instantly share code, notes, and snippets.

@bf4 bf4/null_object.rb
Created Aug 23, 2012

Embed
What would you like to do?
Ruby NullObject pattern
# see http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/
class NullObject
def to_a; []; end
def to_s; ""; end
def to_f; 0.0; end
def to_i; 0; end
def tap; self; end
def nil?; true; end
def present?; false; end
def empty?; true; end
# def !; true; end
def method_missing(*args, &block)
self
end
end
# def Maybe(value)
# case value
# when nil then NullObject.new
# else value
# end
# end
# # We could try another tack. We could define a function to “resolve” the null object back to a nil when needed#k:
# def Value(object)
# case object
# when NullObject then nil
# else object
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.