From d7f3c541a167dba5625e163f6b6d592cb4742dc1 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Fri, 21 Nov 2008 09:47:55 +0100 Subject: [PATCH] Allow optional arguments and/or block for Object#try like Object#send does. Original suggestion by Pat Nakajima. --- .../lib/active_support/core_ext/object/misc.rb | 5 +++-- .../test/core_ext/object_and_class_ext_test.rb | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 50f824c..7c7f673 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -73,6 +73,7 @@ class Object end # 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 : # @@ -81,7 +82,7 @@ class Object # # With try # @person.try(:name) - def try(method) - send(method) if respond_to?(method, true) + def try(method, *args, &block) + send(method, *args, &block) if respond_to?(method, true) end end diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index fbdce56..2f79b6f 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -271,4 +271,11 @@ class ObjectTryTest < Test::Unit::TestCase assert_equal 5, @string.try(:size) 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 -- 1.5.5.3