Skip to content
This repository
Browse code

don't raise NoMethodError the tried method doesn't exists

  • Loading branch information...
commit 29a5aeaae976bf8432d57ec996c7c81932a39de6 1 parent f674aed
Damien Mathieu authored May 21, 2011
2  activesupport/lib/active_support/core_ext/object/try.rb
@@ -28,6 +28,8 @@ class Object
28 28
   def try(*a, &b)
29 29
     if a.empty? && block_given?
30 30
       yield self
+    elsif !a.empty? && !respond_to?(a.first)
+      nil
31 33
32 34
       __send__(*a, &b)
33 35
2  activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -99,7 +99,7 @@ def setup
99 99
   def test_nonexisting_method
100 100
     method = :undefined_method
101 101
     assert !@string.respond_to?(method)
-    assert_raise(NoMethodError) { @string.try(method) }
+    assert_nil @string.try(method)
103 103
104 104
105 105
   def test_valid_method

7 notes on commit 29a5aea

Steve Richert

Could somebody please explain this change?

As I understand it, the purpose of Object#try is to call a method on an object of an expected class, but that could also be nil. In what situation would you want to silently avoid a NoMethodError? If I'm trying a method that doesn't exist in my expected class, I should know about it.

Damien Mathieu

On STI objects where you might have methods defined for some records, but not for others for example.

José Valim
Jon Leighton

Agreed, I think we should revert this.

Andy Lindeman

-1 to this change as well. It's not acceptable to radically change the behavior at this point.

José Valim
Arun Agrawal

This commit 587dd7d also need to revert the fix the failing test. Or might need a fix!

587dd7d commit is not having test.

Please sign in to comment.
Something went wrong with that request. Please try again.