From 29a5aeaae976bf8432d57ec996c7c81932a39de6 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Sat, 21 May 2011 23:43:12 +0200 Subject: [PATCH 1/2] don't raise NoMethodError the tried method doesn't exists --- activesupport/lib/active_support/core_ext/object/try.rb | 2 ++ activesupport/test/core_ext/object_and_class_ext_test.rb | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index e77a9da0ec20d..4797c93e639d7 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 5d68b198f2791..108010a6149cf 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,7 @@ 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_valid_method From a85e00c01c5b9f5592113371c0da5e389129f3f1 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Sun, 22 May 2011 00:32:58 +0200 Subject: [PATCH 2/2] make sure missing method does not fail with arguments --- activesupport/test/core_ext/object_and_class_ext_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) 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 108010a6149cf..beb371d98702a 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -101,6 +101,12 @@ def test_nonexisting_method assert !@string.respond_to?(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 assert_equal 5, @string.try(:size)