diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-11-01 11:06:47 +0100 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-11-02 17:50:12 -0800 |
commit | b540eca5889d7a28fac39c9ec0df715aa89487ce (patch) | |
tree | 76a8ef40d8a9e99f1dc36a5b526b9a4c9c62567c /activesupport/lib/active_support/core_ext/object/to_query.rb | |
parent | 8935854375a6c08acd617beaec30f6fd09a29ea0 (diff) | |
download | rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.tar.gz rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.tar.bz2 rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.zip |
Consolidate Object#to_param and #to_query core extensions
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/to_query.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/to_query.rb | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb new file mode 100644 index 0000000000..3f1540f685 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/to_query.rb @@ -0,0 +1,27 @@ +require 'active_support/core_ext/object/to_param' + +class Object + # Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the + # param name. + # + # 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 + +class Array + # Converts an array into a string suitable for use as a URL query string, + # using the given +key+ as the param name. + # + # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" + def to_query(key) + prefix = "#{key}[]" + collect { |value| value.to_query(prefix) }.join '&' + end +end + +class Hash + alias_method :to_query, :to_param +end |