diff options
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/try.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/try.rb | 19 |
1 files changed, 12 insertions, 7 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index a1c63a0e54..04619124a1 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -5,6 +5,8 @@ class Object # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised # and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass. # + # If try is called without a method to call, it will yield any given block with the object. + # # ==== Examples # # Without try @@ -18,15 +20,18 @@ class Object # +try+ also accepts arguments and/or a block, for the method it is trying # Person.try(:find, 1) # @people.try(:collect) {|p| p.name} + # + # Without a method argument try will yield to the block unless the receiver is nil. + # @person.try { |p| "#{p.first_name} #{p.last_name}" } #-- - # This method definition below is for rdoc purposes only. The alias_method call - # below overrides it as an optimization since +try+ behaves like +Object#send+, - # unless called on +NilClass+. - def try(method, *args, &block) - send(method, *args, &block) + # +try+ behaves like +Object#send+, unless called on +NilClass+. + def try(*a, &b) + if a.empty? && block_given? + yield self + else + __send__(*a, &b) + end end - remove_method :try - alias_method :try, :__send__ end class NilClass #:nodoc: |