33module Kernel
44
55 # Invokes the method identified by the symbol +method+, passing it any
6- # arguments and/or the block specified.
7- #
8- # Unlike regular send, a +NoMethodError+ exception will *not* be raised
9- # if the receiving object is +nil+ (see NilClass#try below).
10- #
11- # Compatible with ActiveSupport's #try, plus an additional Functor
12- # form when called with no arguments and no block.
6+ # arguments and/or the block specified. If the receiver is +nil+, it
7+ # returns +nil+ instead (see NilClass#try below). Otherwise it behaves
8+ # exactly like a normal call (or &.): a method the receiver doesn't have,
9+ # or a private one, raises NoMethodError.
1310 #
1411 # @example.try(:name) #=> "bob"
15- # @example.try { |o| o.name } #=> "bob" (ActiveSupport block form)
16- # @example.try.name #=> "bob" (Facets Functor form)
12+ # @example.try { |o| o.name } #=> "bob"
13+ # @example.try.name #=> "bob" (Functor form)
14+ # nil.try.name #=> nil
15+ #
16+ # NOTE: THIS IS NOT ACTIVESUPPORT'S #try. SINCE RAILS 4.0, ACTIVESUPPORT'S
17+ # #try RETURNS NIL FOR A METHOD THE RECEIVER DOESN'T HAVE, SO A TYPO LIKE
18+ # user.try(:nmae) QUIETLY BECOMES NIL AND HIDES THE BUG. FACETS KEEPS #try
19+ # STRICT AND PUTS THE LENIENT BEHAVIOR IN #try!, WHERE IT BELONGS: IN RUBY,
20+ # THE BANG MARKS THE MORE DANGEROUS VERSION OF A METHOD, AND SWALLOWING A
21+ # MISSING METHOD IS THE DANGEROUS ONE. RAILS HAS THE TWO BACKWARD.
1722 #
1823 def try ( method = nil , *args , &block )
1924 if method
20- __send__ ( method , *args , &block )
25+ public_send ( method , *args , &block )
2126 elsif block_given?
2227 yield self
2328 else
2429 self
2530 end
2631 end
2732
28- # Like #try, but raises NoMethodError if the method doesn't exist
29- # (unless receiver is nil). Compatible with ActiveSupport's #try!.
33+ # Like #try, but also returns +nil+ if the receiver doesn't respond to
34+ # +method+ (or it is private), instead of raising NoMethodError.
35+ #
36+ # @example.try!(:name) #=> "bob"
37+ # @example.try!(:nmae) #=> nil
38+ #
39+ # NOTE: THIS IS THE OPPOSITE OF ACTIVESUPPORT'S #try!, WHICH RAISES. THE
40+ # BANG IS HERE BECAUSE QUIETLY IGNORING A MISSING METHOD IS THE DANGEROUS
41+ # BEHAVIOR; SEE #try ABOVE.
3042 #
3143 def try! ( method = nil , *args , &block )
3244 if method
33- public_send ( method , *args , &block )
45+ public_send ( method , *args , &block ) if respond_to? ( method )
3446 elsif block_given?
3547 yield self
3648 else
@@ -40,7 +52,6 @@ def try!(method=nil, *args, &block)
4052
4153end
4254
43-
4455class NilClass
4556
4657 # See Kernel#try.
0 commit comments