aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/object/misc.rb
diff options
context:
space:
mode:
authorHongli Lai (Phusion) <hongli@phusion.nl>2008-12-03 19:30:35 +0100
committerHongli Lai (Phusion) <hongli@phusion.nl>2008-12-03 19:30:35 +0100
commitccb96f2297e8783165cba764e9b5d51e1a15ff87 (patch)
tree3229e6fdddc42054615514d843c555e341003033 /activesupport/lib/active_support/core_ext/object/misc.rb
parentfb2325e35855d62abd2c76ce03feaa3ca7992e4f (diff)
parent761a633a9c0a45d76ef3ed10da97e3696c3ded79 (diff)
downloadrails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.tar.gz
rails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.tar.bz2
rails-ccb96f2297e8783165cba764e9b5d51e1a15ff87.zip
Merge commit 'origin/master' into savepoints
Conflicts: activerecord/lib/active_record/fixtures.rb activerecord/test/cases/defaults_test.rb
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/misc.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/object/misc.rb18
1 files changed, 18 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..46f9c7d676 100644
--- a/activesupport/lib/active_support/core_ext/object/misc.rb
+++ b/activesupport/lib/active_support/core_ext/object/misc.rb
@@ -71,4 +71,22 @@ 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.
+ # It will also forward any arguments and/or block like Object#send does.
+ #
+ # ==== Example :
+ #
+ # # Without try
+ # @person ? @person.name : nil
+ #
+ # With try
+ # @person.try(:name)
+ #
+ # # 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