Permalink
Browse files

Merge pull request #100 from knu/master

Accept an array of strings (and IO-likes) as a query value.
  • Loading branch information...
2 parents 727ad77 + 8ae4719 commit 754e638d3d675622213542e6d1bddc466ebf37ef @nahi committed Aug 11, 2012
Showing with 40 additions and 5 deletions.
  1. +28 −5 lib/httpclient/http.rb
  2. +12 −0 test/test_httpclient.rb
View
33 lib/httpclient/http.rb
@@ -826,13 +826,36 @@ def create_query_part_str(query) # :nodoc:
end
end
+ def Array.try_convert(value)
+ return value if value.instance_of?(Array)
+ return nil if !value.respond_to?(:to_ary)
+ converted = value.to_ary
+ return converted if converted.instance_of?(Array)
+
+ cname = value.class.name
+ raise TypeError, "can't convert %s to %s (%s#%s gives %s)" %
+ [cname, Array.name, cname, :to_ary, converted.class.name]
+ end unless Array.respond_to?(:try_convert)
+
def escape_query(query) # :nodoc:
- query.collect { |attr, value|
- if value.respond_to?(:read)
- value = value.read
+ pairs = []
+ query.each { |attr, value|
+ left = escape(attr.to_s) << '='
+ if values = Array.try_convert(value)
+ values.each { |value|
+ if value.respond_to?(:read)
+ value = value.read
+ end
+ pairs.push(left + escape(value.to_s))
+ }
+ else
+ if value.respond_to?(:read)
+ value = value.read
+ end
+ pairs.push(left << escape(value.to_s))
end
- escape(attr.to_s) << '=' << escape(value.to_s)
- }.join('&')
+ }
+ pairs.join('&')
end
# from CGI.escape
View
12 test/test_httpclient.rb
@@ -910,6 +910,18 @@ def test_get_query
assert_equal({}, check_query_get(''))
assert_equal({'1'=>'2'}, check_query_get({1=>StringIO.new('2')}))
assert_equal({'1'=>'2', '3'=>'4'}, check_query_get(StringIO.new('3=4&1=2')))
+
+ hash = check_query_get({"a"=>["A","a"], "B"=>"b"})
+ assert_equal({'a'=>'A', 'B'=>'b'}, hash)
+ assert_equal(['A','a'], hash['a'].to_ary)
+
+ hash = check_query_get({"a"=>WEBrick::HTTPUtils::FormData.new("A","a"), "B"=>"b"})
+ assert_equal({'a'=>'A', 'B'=>'b'}, hash)
+ assert_equal(['A','a'], hash['a'].to_ary)
+
+ hash = check_query_get({"a"=>[StringIO.new("A"),StringIO.new("a")], "B"=>StringIO.new("b")})
+ assert_equal({'a'=>'A', 'B'=>'b'}, hash)
+ assert_equal(['A','a'], hash['a'].to_ary)
end
def test_post_body

0 comments on commit 754e638

Please sign in to comment.