Skip to content

Instantly share code, notes, and snippets.

@makoto
Created November 4, 2010 00:31
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/661951 to your computer and use it in GitHub Desktop.
Save makoto/661951 to your computer and use it in GitHub Desktop.
try_scope #2
class Object
def try_scope(&block)
block.call(self)
rescue NoMethodError => e
# Is there better ways than doing grep of the error message?
if e.message.grep(/NilClass/).empty?
raise
else
nil
end
end
end
require "test/unit"
class TestTryScope < Test::Unit::TestCase
def test_should_return_nil_when_nil_calls_a_method
assert_nil(nil.try_scope{|a| a.foo})
end
def test_should_return_nil_when_nil_calls_chained_methods
assert_nil(nil.try_scope{|a| a.map{|b| b.capitalize}.map{|b| b.downcase}})
end
def test_should_return_nil_when_an_array_with_nil_calls_chained_method
assert_nil(['1', nil].try_scope{|a| a.map{|b| b.upcase}.map{|b| b.downcase}})
end
def test_should_return_nil_when_chained_method_returns_nil
# Same as "class Object ; def nilme ; nil ; end ; end"
Object.class_eval do
define_method :nilme do
nil
end
end
assert_nil("foo".try_scope{|a| a.capitalize.nilme.downcase})
end
def test_should_raise_error_if_non_nil_value_calls_undefined_method
assert_raise(NoMethodError) do
['a', 'b', 'c'].try_scope{|a| a.map{|b| b.capitalize}.map{|b| b.foo(1)}}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment