Skip to content

Instantly share code, notes, and snippets.

@makoto
Created November 2, 2010 19:59
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 makoto/660194 to your computer and use it in GitHub Desktop.
Save makoto/660194 to your computer and use it in GitHub Desktop.
try_scope
# Inspired by http://intridea.com/2010/11/2/calling-methods-on-potential-nil-objects-in-rails
class Object
def try_scope(&block)
# self is nil if it is called by NilClass object
block.call(self) if self
end
end
p ['a', 'b', 'c'].try_scope{|a| a.map{|b| b.capitalize}.map{|b| b.downcase}} # => ["a", "b", "c"]
p nil.try_scope{|a| a.map{|b| b.capitalize}.map{|b| b.downcase}.foo(1)} # => nil
p ['a', 'b', 'c'].try_scope{|a| a.map{|b| b.capitalize}.map{|b| b.foo(1)}} # => NoMethodError: undefined method ‘foo’ for "A":String
# Note:
# The alternative is to use "Black Halls" technique introduced at
# http://www.pragprog.com/magazines/2010-01/much-ado-about-nothing
#
# class NilClass
# def method_missing(*); end
# end
#
# This absorbs any errors raised from nil, but this may hinder bugs as mentioned in the article itself.
# By using try_scope{}, you can restrict the use of black halls only to the place you want to apply.
#
# The another argument may be that we should not chain too many methods in general.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment