Merged updates from trunk into stable branch
[feedcatcher.git] / vendor / rails / activesupport / lib / active_support / core_ext / try.rb
1 class Object
2 # Invokes the method identified by the symbol +method+, passing it any arguments
3 # and/or the block specified, just like the regular Ruby <tt>Object#send</tt> does.
4 #
5 # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
6 # and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
7 #
8 # ==== Examples
9 #
10 # Without try
11 # @person && @person.name
12 # or
13 # @person ? @person.name : nil
14 #
15 # With try
16 # @person.try(:name)
17 #
18 # +try+ also accepts arguments and/or a block, for the method it is trying
19 # Person.try(:find, 1)
20 # @people.try(:collect) {|p| p.name}
21 #--
22 # This method definition below is for rdoc purposes only. The alias_method call
23 # below overrides it as an optimization since +try+ behaves like +Object#send+,
24 # unless called on +NilClass+.
25 def try(method, *args, &block)
26 send(method, *args, &block)
27 end
28 remove_method :try
29 alias_method :try, :__send__
30 end
31
32 class NilClass
33 def try(*args)
34 nil
35 end
36 end