Created
March 11, 2013 11:25
-
-
Save krisleech/5133588 to your computer and use it in GitHub Desktop.
NullObject addition (http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/)
This file contains hidden or 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
class NullObject < BasicObject | |
def initialize(represents = nil) | |
@represents = represents || 'NullObject' | |
end | |
def nil?; true; end | |
def present?; false; end | |
def blank?; true; end | |
def empty?; true; end | |
def !; true; end | |
def to_a; []; end | |
def to_s; ''; end | |
def to_f; 0.0; end | |
def to_i; 0; end | |
def to_str; to_s; end | |
def inspect | |
"<#{represents}>" | |
end | |
def method_missing(*args, &block) | |
self | |
end | |
private | |
attr_reader :represents | |
end | |
date = nil || NullObject.new('NullDate') | |
date.inspect # => '<NullDate>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment