Skip to content

Instantly share code, notes, and snippets.

@mrbrdo
Created September 27, 2012 08:00
Show Gist options
  • Save mrbrdo/3792789 to your computer and use it in GitHub Desktop.
Save mrbrdo/3792789 to your computer and use it in GitHub Desktop.
chaining methods on nil (null object pattren)
# null object pattern Objective-C style (togglable)
# more elegant: https://gist.github.com/3792804
def null_chain
unless NilClass.instance_variable_defined?(:@null_chain)
NilClass.class_eval do
alias_method :nc_mm_orig, :method_missing
def method_missing(name, *args, &block)
if self.class.null_chain?
nil
else
nc_mm_orig(name, *args, &block)
end
end
def self.null_chain?
@null_chain
end
end
end
NilClass.instance_variable_set(:@null_chain, true)
yield.tap do
NilClass.instance_variable_set(:@null_chain, false)
end
end
null_chain do
@abrakadabra.whatever.work
@abrakadabra.whatever.work
end
begin
@abrakadabra.whatever.work
rescue
puts "it works"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment