Skip to content

Instantly share code, notes, and snippets.

@bf4
Created August 23, 2012 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bf4/3438476 to your computer and use it in GitHub Desktop.
Save bf4/3438476 to your computer and use it in GitHub Desktop.
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