mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Added Hash#to_query to turn a hash of values into a form-encoded query string [Nicholas Seckar]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6038 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
parent
5544231caf
commit
35433859bd
3 changed files with 47 additions and 0 deletions
|
@ -1,5 +1,7 @@
|
|||
*SVN*
|
||||
|
||||
* Added Hash#to_query to turn a hash of values into a form-encoded query string [Nicholas Seckar]
|
||||
|
||||
* Increase test coverage for subclasses_of. Closes #7335. [Roman2K, Nicholas Seckar]
|
||||
|
||||
* Remove unused code from Duration#inspect. Closes #7180. [Rich Collins]
|
||||
|
|
|
@ -1,5 +1,23 @@
|
|||
require 'date'
|
||||
require 'xml_simple'
|
||||
require 'cgi'
|
||||
|
||||
# Extensions needed for Hash#to_query
|
||||
class Object
|
||||
def to_param #:nodoc:
|
||||
to_s
|
||||
end
|
||||
|
||||
def to_query(key) #:nodoc:
|
||||
"#{key}=#{CGI.escape(to_param)}"
|
||||
end
|
||||
end
|
||||
|
||||
class Array
|
||||
def to_query(key) #:nodoc:
|
||||
collect { |value| value.to_query("#{key}[]") } * '&'
|
||||
end
|
||||
end
|
||||
|
||||
module ActiveSupport #:nodoc:
|
||||
module CoreExtensions #:nodoc:
|
||||
|
@ -27,6 +45,12 @@ module ActiveSupport #:nodoc:
|
|||
klass.extend(ClassMethods)
|
||||
end
|
||||
|
||||
def to_query(namespace = nil)
|
||||
collect do |key, value|
|
||||
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
|
||||
end * '&'
|
||||
end
|
||||
|
||||
def to_xml(options = {})
|
||||
options[:indent] ||= 2
|
||||
options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
|
||||
|
|
|
@ -527,3 +527,24 @@ class HashToXmlTest < Test::Unit::TestCase
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
class QueryTest < Test::Unit::TestCase
|
||||
def test_simple_conversion
|
||||
assert_equal 'a=10', {:a => 10}.to_query
|
||||
end
|
||||
|
||||
def test_nested_conversion
|
||||
assert_equal 'person[name]=Nicholas&person[login]=seckar',
|
||||
{:person => {:name => 'Nicholas', :login => 'seckar'}}.to_query
|
||||
end
|
||||
|
||||
def test_multiple_nested
|
||||
assert_equal 'account[person][id]=20&person[id]=10',
|
||||
{:person => {:id => 10}, :account => {:person => {:id => 20}}}.to_query
|
||||
end
|
||||
|
||||
def test_array_values
|
||||
assert_equal 'person[id][]=10&person[id][]=20',
|
||||
{:person => {:id => [10, 20]}}.to_query
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue