aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2008-11-19 19:36:42 +0530
committerPratik Naik <pratiknaik@gmail.com>2008-11-19 19:36:42 +0530
commit51730792ca930a896361eb92354a42bc56903de1 (patch)
treeda1992628081de9c2c0f09b64e1d55893d6e2bcd /activesupport/lib
parent51a19ae2bf33e66b23ff5c91bf584b2efa9e669f (diff)
downloadrails-51730792ca930a896361eb92354a42bc56903de1.tar.gz
rails-51730792ca930a896361eb92354a42bc56903de1.tar.bz2
rails-51730792ca930a896361eb92354a42bc56903de1.zip
Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]
Diffstat (limited to 'activesupport/lib')
-rw-r--r--activesupport/lib/active_support/core_ext/object/misc.rb13
1 files changed, 13 insertions, 0 deletions
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