From 236a095566acd8fca7bfa0a9ab7dd65d95a0a300 Mon Sep 17 00:00:00 2001 From: Josh Susser Date: Fri, 16 Jan 2009 17:26:08 -0800 Subject: [PATCH] refactored Object#try to use inheritance --- .../lib/active_support/core_ext/object/misc.rb | 17 ------------- activesupport/lib/active_support/core_ext/try.rb | 25 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 17 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/try.rb diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index c0a109e..4acdfa3 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -87,21 +87,4 @@ class Object 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) unless self.nil? - end end diff --git a/activesupport/lib/active_support/core_ext/try.rb b/activesupport/lib/active_support/core_ext/try.rb new file mode 100644 index 0000000..5ef9857 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/try.rb @@ -0,0 +1,25 @@ +class Object + alias_method :try, :__send__ +end + +class NilClass + # 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 + # # or + # @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(*args) + nil + end +end -- 1.6.0.4