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') 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