Skip to content

Commit

Permalink
Merge pull request rails#1195 from dmathieu/try_undefined_method
Browse files Browse the repository at this point in the history
Don't raise NoMethodError the tried method doesn't exists
  • Loading branch information
dhh committed May 22, 2011
2 parents f674aed + a85e00c commit 073f80e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 2 additions & 0 deletions activesupport/lib/active_support/core_ext/object/try.rb
Expand Up @@ -28,6 +28,8 @@ class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
elsif !a.empty? && !respond_to?(a.first)
nil
else
__send__(*a, &b)
end
Expand Down
8 changes: 7 additions & 1 deletion activesupport/test/core_ext/object_and_class_ext_test.rb
Expand Up @@ -99,7 +99,13 @@ def setup
def test_nonexisting_method
method = :undefined_method
assert !@string.respond_to?(method)
assert_raise(NoMethodError) { @string.try(method) }
assert_nil @string.try(method)
end

def test_nonexisting_method_with_arguments
method = :undefined_method
assert !@string.respond_to?(method)
assert_nil @string.try(method, 'llo', 'y')
end

def test_valid_method
Expand Down

0 comments on commit 073f80e

Please sign in to comment.