aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/object/try.rb
diff options
context:
space:
mode:
authorraggi <jftucker@gmail.com>2010-10-27 06:10:01 +0800
committerJosé Valim <jose.valim@gmail.com>2010-11-14 17:23:44 +0800
commite6d14279b881d8482c124bd55d0830a7ddcbcb0e (patch)
treec248862e1b261b86afcdebe44fa773f1101f71c1 /activesupport/lib/active_support/core_ext/object/try.rb
parentf43e5d160bf9708ad50b58c8168e38579769e024 (diff)
downloadrails-e6d14279b881d8482c124bd55d0830a7ddcbcb0e.tar.gz
rails-e6d14279b881d8482c124bd55d0830a7ddcbcb0e.tar.bz2
rails-e6d14279b881d8482c124bd55d0830a7ddcbcb0e.zip
Add support for try to just yield the object to a block if no method is to be called. Kind of like a tap_if_present.
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/try.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb14
1 files changed, 13 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 48e9d04787..4d742b9ed2 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -8,6 +8,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
@@ -21,10 +23,20 @@ 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 reciever is nil.
+ # @person.try { |p| "#{p.first_name} #{p.last_name}" }
#--
# +try+ behaves like +Object#send+, unless called on +NilClass+.
- alias_method :try, :__send__
+ def try(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
+ __send__(*a, &b)
+ end
+ end
+
end
class NilClass #:nodoc: