From 51730792ca930a896361eb92354a42bc56903de1 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 19 Nov 2008 19:36:42 +0530 Subject: Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath] --- activesupport/lib/active_support/core_ext/object/misc.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activesupport/lib/active_support/core_ext/object/misc.rb') diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index cd0a04d32a..50f824c358 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -71,4 +71,17 @@ class Object def acts_like?(duck) respond_to? "acts_like_#{duck}?" end + + # Tries to send the method only if object responds to it. Return +nil+ otherwise. + # + # ==== Example : + # + # # Without try + # @person ? @person.name : nil + # + # With try + # @person.try(:name) + def try(method) + send(method) if respond_to?(method, true) + end end -- cgit v1.2.3 From 823b623fe2de8846c37aa13250010809ac940b57 Mon Sep 17 00:00:00 2001 From: Eloy Duran Date: Fri, 21 Nov 2008 09:47:55 +0100 Subject: 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 --- activesupport/lib/active_support/core_ext/object/misc.rb | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'activesupport/lib/active_support/core_ext/object/misc.rb') diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 50f824c358..46f9c7d676 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,11 @@ class Object # # With try # @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 -- cgit v1.2.3