mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #1195 from dmathieu/try_undefined_method
Don't raise NoMethodError the tried method doesn't exists
This commit is contained in:
commit
073f80eaa8
2 changed files with 9 additions and 1 deletions
|
@ -28,6 +28,8 @@ class Object
|
||||||
def try(*a, &b)
|
def try(*a, &b)
|
||||||
if a.empty? && block_given?
|
if a.empty? && block_given?
|
||||||
yield self
|
yield self
|
||||||
|
elsif !a.empty? && !respond_to?(a.first)
|
||||||
|
nil
|
||||||
else
|
else
|
||||||
__send__(*a, &b)
|
__send__(*a, &b)
|
||||||
end
|
end
|
||||||
|
|
|
@ -99,7 +99,13 @@ class ObjectTryTest < Test::Unit::TestCase
|
||||||
def test_nonexisting_method
|
def test_nonexisting_method
|
||||||
method = :undefined_method
|
method = :undefined_method
|
||||||
assert !@string.respond_to?(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
|
end
|
||||||
|
|
||||||
def test_valid_method
|
def test_valid_method
|
||||||
|
|
Loading…
Reference in a new issue