diff options
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/conversions.rb | 3 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/misc.rb | 18 |
2 files changed, 20 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb index ad752f0fc5..278b856c45 100644 --- a/activesupport/lib/active_support/core_ext/object/conversions.rb +++ b/activesupport/lib/active_support/core_ext/object/conversions.rb @@ -9,6 +9,7 @@ class Object # # Note: This method is defined as a default implementation for all Objects for Hash#to_query to work. def to_query(key) + require 'cgi' unless defined?(CGI) && defined?(CGI::escape) "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" end -end
\ No newline at end of file +end 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 |