Skip to content
This repository
Browse code

will now return nil instead of raise a NoMethodError if the receivin…

…g object does not implement the method
  • Loading branch information...
commit 99ea1a875b06feb4346869f371e2a57a2cc0a0fc 1 parent 3205c76
David Heinemeier Hansson authored July 27, 2012
2  activesupport/CHANGELOG.md
Source Rendered
... ...
@@ -1,5 +1,7 @@
1 1
 ## Rails 4.0.0 (unreleased) ##
2 2
 
  3
+*   `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method *DHH*
  4
+
3 5
 *   `Time#change` now works with time values with offsets other than UTC or the local time zone. *Andrew White*
4 6
 
5 7
 *   `ActiveSupport::Callbacks`: deprecate usage of filter object with `#before` and `#after` methods as `around` callback. *Bogdan Gusiev*
5  activesupport/lib/active_support/core_ext/object/try.rb
@@ -5,6 +5,9 @@ class Object
5 5
   # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
6 6
   # and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
7 7
   #
  8
+  # This is also true if the receiving object does not implemented the tried method. It will
  9
+  # return +nil+ in that case as well.
  10
+  #
8 11
   # If try is called without a method to call, it will yield any given block with the object.
9 12
   #
10 13
   # Please also note that +try+ is defined on +Object+, therefore it won't work with
@@ -31,7 +34,7 @@ def try(*a, &b)
31 34
     if a.empty? && block_given?
32 35
       yield self
33 36
     else
34  
-      public_send(*a, &b)
  37
+      public_send(*a, &b) if respond_to?(a.first)
35 38
     end
36 39
   end
37 40
 end
8  activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -99,13 +99,13 @@ def setup
99 99
   def test_nonexisting_method
100 100
     method = :undefined_method
101 101
     assert !@string.respond_to?(method)
102  
-    assert_raise(NoMethodError) { @string.try(method) }
  102
+    assert_nil @string.try(method)
103 103
   end
104 104
 
105 105
   def test_nonexisting_method_with_arguments
106 106
     method = :undefined_method
107 107
     assert !@string.respond_to?(method)
108  
-    assert_raise(NoMethodError) { @string.try(method, 'llo', 'y') }
  108
+    assert_nil @string.try(method, 'llo', 'y')
109 109
   end
110 110
 
111 111
   def test_valid_method
@@ -124,7 +124,7 @@ def test_nil_to_type
124 124
     assert_nil nil.try(:to_s)
125 125
     assert_nil nil.try(:to_i)
126 126
   end
127  
-
  127
+  
128 128
   def test_false_try
129 129
     assert_equal 'false', false.try(:to_s)
130 130
   end
@@ -148,6 +148,6 @@ def private_method
148 148
       end
149 149
     end
150 150
 
151  
-    assert_raise(NoMethodError) { klass.new.try(:private_method) }
  151
+    assert_nil klass.new.try(:private_method)
152 152
   end
153 153
 end

0 notes on commit 99ea1a8

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