aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2011-05-21 17:56:44 -0700
committerDavid Heinemeier Hansson <david@loudthinking.com>2011-05-21 17:56:44 -0700
commit073f80eaa849c479fe547c3c34430db3c91702fb (patch)
treee751acb2eab3b97773298dbe8eece95569fd8351
parentf674aed150e4c87cd9f149307313114a597dfa8b (diff)
parenta85e00c01c5b9f5592113371c0da5e389129f3f1 (diff)
downloadrails-073f80eaa849c479fe547c3c34430db3c91702fb.tar.gz
rails-073f80eaa849c479fe547c3c34430db3c91702fb.tar.bz2
rails-073f80eaa849c479fe547c3c34430db3c91702fb.zip
Merge pull request #1195 from dmathieu/try_undefined_method
Don't raise NoMethodError the tried method doesn't exists
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb2
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb8
2 files changed, 9 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index e77a9da0ec..4797c93e63 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -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
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
index 5d68b198f2..beb371d987 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -99,7 +99,13 @@ class ObjectTryTest < Test::Unit::TestCase
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