diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb index b7d4434e85e453f9f28f9e756446973c49fbd237..c828e84112abdbb574dd23f620e64ea13cd2607b 100644 --- a/activesupport/lib/active_support/core_ext/array/conversions.rb +++ b/activesupport/lib/active_support/core_ext/array/conversions.rb @@ -29,6 +29,15 @@ def to_param join '/' end + # Converts an array into a string suitable for use as a URL query string, using the given key as the + # param name. + # + # ==== Example: + # ['Rails', 'coding'].to_query('hobbies') => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" + def to_query(key) + collect { |value| value.to_query("#{key}[]") } * '&' + end + def self.included(base) #:nodoc: base.class_eval do alias_method :to_default_s, :to_s diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index e196c5d7b943baab18ed6015dd8fc9494fdbc936..8021dfa87addfc34b0936b6c438b0db51311a5ac 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -4,23 +4,6 @@ require 'builder' require 'xmlsimple' -# Extensions needed for Hash#to_query -class Object - def to_param #:nodoc: - to_s - end - - def to_query(key) #:nodoc: - "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" - end -end - -class Array - def to_query(key) #:nodoc: - collect { |value| value.to_query("#{key}[]") } * '&' - end -end - # Locked down XmlSimple#xml_in_string class XmlSimple # Same as xml_in but doesn't try to smartly shoot itself in the foot. @@ -100,6 +83,13 @@ def self.included(klass) klass.extend(ClassMethods) end + # Converts a hash into a string suitable for use as a URL query string. An optional namespace can be + # passed to enclose the param names (see example below). + # + # ==== Example: + # { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish" + # + # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" def to_query(namespace = nil) collect do |key, value| value.to_query(namespace ? "#{namespace}[#{key}]" : key) diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb index 3b055d31851b45affaad8cf5d513ee0ed5f40fb5..bbc7d8167296a8fd453a57a3aac4e8ed3b4dc419 100644 --- a/activesupport/lib/active_support/core_ext/object.rb +++ b/activesupport/lib/active_support/core_ext/object.rb @@ -1,3 +1,4 @@ +require 'active_support/core_ext/object/conversions' require 'active_support/core_ext/object/extending' require 'active_support/core_ext/object/instance_variables' require 'active_support/core_ext/object/misc'