aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/object/try.rb
diff options
context:
space:
mode:
authorGonçalo Silva <goncalossilva@gmail.com>2011-03-24 17:21:17 +0000
committerGonçalo Silva <goncalossilva@gmail.com>2011-03-24 17:21:17 +0000
commit9887f238871bb2dd73de6ce8855615bcc5d8d079 (patch)
tree74fa9ff9524a51701cfa23f708b3f777c65b7fe5 /activesupport/lib/active_support/core_ext/object/try.rb
parentaff821508a16245ebc03510ba29c70379718dfb7 (diff)
parent5214e73850916de3c9127d35a4ecee0424d364a3 (diff)
downloadrails-9887f238871bb2dd73de6ce8855615bcc5d8d079.tar.gz
rails-9887f238871bb2dd73de6ce8855615bcc5d8d079.tar.bz2
rails-9887f238871bb2dd73de6ce8855615bcc5d8d079.zip
Merge branch 'master' of https://github.com/rails/rails
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/try.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb19
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: