1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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.

This commit is contained in:
raggi 2010-10-27 06:10:01 +08:00 committed by José Valim
parent f43e5d160b
commit e6d14279b8
2 changed files with 23 additions and 1 deletions

View file

@ -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:

View file

@ -134,4 +134,14 @@ class ObjectTryTest < Test::Unit::TestCase
def test_false_try
assert_equal 'false', false.try(:to_s)
end
def test_try_only_block
assert_equal @string.reverse, @string.try { |s| s.reverse }
end
def test_try_only_block_nil
ran = false
nil.try { ran = true }
assert_equal false, ran
end
end