From 04998cd0c92a13332844d04145a4ede3184c7bd0 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 27 Jul 2012 12:33:02 -0500 Subject: Add Object#try! with the old NoMethodError raising behavior --- activesupport/lib/active_support/core_ext/object/try.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'activesupport/lib') diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index a2d5caa7df..9974b61078 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -37,6 +37,16 @@ class Object public_send(*a, &b) if respond_to?(a.first) end end + + # Same as #try, but will raise a NoMethodError exception if the receiving is not nil and + # does not implemented the tried method. + def try!(*a, &b) + if a.empty? && block_given? + yield self + else + public_send(*a, &b) + end + end end class NilClass @@ -53,4 +63,8 @@ class NilClass def try(*args) nil end + + def try!(*args) + nil + end end -- cgit v1.2.3