Skip to content
This repository
Browse code

Merge pull request #100 from knu/master

Accept an array of strings (and IO-likes) as a query value.
  • Loading branch information...
commit 754e638d3d675622213542e6d1bddc466ebf37ef 2 parents 727ad77 + 8ae4719
Hiroshi Nakamura authored

Showing 2 changed files with 40 additions and 5 deletions. Show diff stats Hide diff stats

  1. +28 5 lib/httpclient/http.rb
  2. +12 0 test/test_httpclient.rb
33 lib/httpclient/http.rb
@@ -826,13 +826,36 @@ def create_query_part_str(query) # :nodoc:
826 826 end
827 827 end
828 828
  829 + def Array.try_convert(value)
  830 + return value if value.instance_of?(Array)
  831 + return nil if !value.respond_to?(:to_ary)
  832 + converted = value.to_ary
  833 + return converted if converted.instance_of?(Array)
  834 +
  835 + cname = value.class.name
  836 + raise TypeError, "can't convert %s to %s (%s#%s gives %s)" %
  837 + [cname, Array.name, cname, :to_ary, converted.class.name]
  838 + end unless Array.respond_to?(:try_convert)
  839 +
829 840 def escape_query(query) # :nodoc:
830   - query.collect { |attr, value|
831   - if value.respond_to?(:read)
832   - value = value.read
  841 + pairs = []
  842 + query.each { |attr, value|
  843 + left = escape(attr.to_s) << '='
  844 + if values = Array.try_convert(value)
  845 + values.each { |value|
  846 + if value.respond_to?(:read)
  847 + value = value.read
  848 + end
  849 + pairs.push(left + escape(value.to_s))
  850 + }
  851 + else
  852 + if value.respond_to?(:read)
  853 + value = value.read
  854 + end
  855 + pairs.push(left << escape(value.to_s))
833 856 end
834   - escape(attr.to_s) << '=' << escape(value.to_s)
835   - }.join('&')
  857 + }
  858 + pairs.join('&')
836 859 end
837 860
838 861 # from CGI.escape
12 test/test_httpclient.rb
@@ -910,6 +910,18 @@ def test_get_query
910 910 assert_equal({}, check_query_get(''))
911 911 assert_equal({'1'=>'2'}, check_query_get({1=>StringIO.new('2')}))
912 912 assert_equal({'1'=>'2', '3'=>'4'}, check_query_get(StringIO.new('3=4&1=2')))
  913 +
  914 + hash = check_query_get({"a"=>["A","a"], "B"=>"b"})
  915 + assert_equal({'a'=>'A', 'B'=>'b'}, hash)
  916 + assert_equal(['A','a'], hash['a'].to_ary)
  917 +
  918 + hash = check_query_get({"a"=>WEBrick::HTTPUtils::FormData.new("A","a"), "B"=>"b"})
  919 + assert_equal({'a'=>'A', 'B'=>'b'}, hash)
  920 + assert_equal(['A','a'], hash['a'].to_ary)
  921 +
  922 + hash = check_query_get({"a"=>[StringIO.new("A"),StringIO.new("a")], "B"=>StringIO.new("b")})
  923 + assert_equal({'a'=>'A', 'B'=>'b'}, hash)
  924 + assert_equal(['A','a'], hash['a'].to_ary)
913 925 end
914 926
915 927 def test_post_body

0 comments on commit 754e638

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