mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Allow optional arguments and/or block for Object#try like Object#send does. [#1425 state:resolved]
Original suggestion by Pat Nakajima. Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
parent
fffb1da3f2
commit
823b623fe2
2 changed files with 14 additions and 2 deletions
|
@ -73,6 +73,7 @@ class Object
|
||||||
end
|
end
|
||||||
|
|
||||||
# Tries to send the method only if object responds to it. Return +nil+ otherwise.
|
# Tries to send the method only if object responds to it. Return +nil+ otherwise.
|
||||||
|
# It will also forward any arguments and/or block like Object#send does.
|
||||||
#
|
#
|
||||||
# ==== Example :
|
# ==== Example :
|
||||||
#
|
#
|
||||||
|
@ -81,7 +82,11 @@ class Object
|
||||||
#
|
#
|
||||||
# With try
|
# With try
|
||||||
# @person.try(:name)
|
# @person.try(:name)
|
||||||
def try(method)
|
#
|
||||||
send(method) if respond_to?(method, true)
|
# # try also accepts arguments/blocks for the method it is trying
|
||||||
|
# Person.try(:find, 1)
|
||||||
|
# @people.try(:map) {|p| p.name}
|
||||||
|
def try(method, *args, &block)
|
||||||
|
send(method, *args, &block) if respond_to?(method, true)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -271,4 +271,11 @@ class ObjectTryTest < Test::Unit::TestCase
|
||||||
assert_equal 5, @string.try(:size)
|
assert_equal 5, @string.try(:size)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_argument_forwarding
|
||||||
|
assert_equal 'Hey', @string.try(:sub, 'llo', 'y')
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_block_forwarding
|
||||||
|
assert_equal 'Hey', @string.try(:sub, 'llo') { |match| 'y' }
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue