Skip to content
This repository
Browse code

Added Hash#to_query to turn a hash of values into a form-encoded quer…

…y string [Nicholas Seckar]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6038 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit 35433859bd9995a9802abc38b1aba379c0019dff 1 parent 5544231
David Heinemeier Hansson authored January 24, 2007
2  activesupport/CHANGELOG
... ...
@@ -1,5 +1,7 @@
1 1
 *SVN*
2 2
 
  3
+* Added Hash#to_query to turn a hash of values into a form-encoded query string [Nicholas Seckar]
  4
+
3 5
 * Increase test coverage for subclasses_of. Closes #7335. [Roman2K, Nicholas Seckar]
4 6
 
5 7
 * Remove unused code from Duration#inspect.  Closes #7180.  [Rich Collins]
24  activesupport/lib/active_support/core_ext/hash/conversions.rb
... ...
@@ -1,5 +1,23 @@
1 1
 require 'date'
2 2
 require 'xml_simple'
  3
+require 'cgi'
  4
+
  5
+# Extensions needed for Hash#to_query
  6
+class Object
  7
+  def to_param #:nodoc:
  8
+    to_s
  9
+  end
  10
+
  11
+  def to_query(key) #:nodoc:
  12
+    "#{key}=#{CGI.escape(to_param)}"
  13
+  end
  14
+end
  15
+
  16
+class Array
  17
+  def to_query(key) #:nodoc:
  18
+    collect { |value| value.to_query("#{key}[]") } * '&'
  19
+  end
  20
+end
3 21
 
4 22
 module ActiveSupport #:nodoc:
5 23
   module CoreExtensions #:nodoc:
@@ -27,6 +45,12 @@ def self.included(klass)
27 45
           klass.extend(ClassMethods)
28 46
         end
29 47
 
  48
+        def to_query(namespace = nil)
  49
+          collect do |key, value|
  50
+            value.to_query(namespace ? "#{namespace}[#{key}]" : key)
  51
+          end * '&'
  52
+        end
  53
+
30 54
         def to_xml(options = {})
31 55
           options[:indent] ||= 2
32 56
           options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
21  activesupport/test/core_ext/hash_ext_test.rb
@@ -527,3 +527,24 @@ def test_kernel_method_names_to_xml
527 527
     end
528 528
   end
529 529
 end
  530
+
  531
+class QueryTest < Test::Unit::TestCase
  532
+  def test_simple_conversion
  533
+    assert_equal 'a=10', {:a => 10}.to_query
  534
+  end
  535
+  
  536
+  def test_nested_conversion
  537
+    assert_equal 'person[name]=Nicholas&person[login]=seckar',
  538
+      {:person => {:name => 'Nicholas', :login => 'seckar'}}.to_query
  539
+  end
  540
+  
  541
+  def test_multiple_nested
  542
+    assert_equal 'account[person][id]=20&person[id]=10',
  543
+      {:person => {:id => 10}, :account => {:person => {:id => 20}}}.to_query
  544
+  end
  545
+  
  546
+  def test_array_values
  547
+    assert_equal 'person[id][]=10&person[id][]=20',
  548
+      {:person => {:id => [10, 20]}}.to_query
  549
+  end
  550
+end

0 notes on commit 3543385

Please sign in to comment.
Something went wrong with that request. Please try again.