Created
August 23, 2012 16:39
-
-
Save bf4/3438476 to your computer and use it in GitHub Desktop.
Ruby NullObject pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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