URI.encode_www_form
# File tmp/rubies/ruby-4.0.0/lib/uri/common.rb, line 567
def self.encode_www_form(enum, enc=nil)
enum.map do |k,v|
if v.nil?
encode_www_form_component(k, enc)
elsif v.respond_to?(:to_ary)
v.to_ary.map do |w|
str = encode_www_form_component(k, enc)
unless w.nil?
str << '='
str << encode_www_form_component(w, enc)
end
end.join('&')
else
str = encode_www_form_component(k, enc)
str << '='
str << encode_www_form_component(v, enc)
end
end.join('&')
end
Returns a URL-encoded string derived from the given Enumerable enum.
The result is suitable for use as form data for an HTTP request whose Content-Type is 'application/x-www-form-urlencoded'.
The returned string consists of the elements of enum, each converted to one or more URL-encoded strings, and all joined with character '&'.
Simple examples:
URI.encode_www_form([['foo', 0], ['bar', 1], ['baz', 2]]) # => "foo=0&bar=1&baz=2" URI.encode_www_form({foo: 0, bar: 1, baz: 2}) # => "foo=0&bar=1&baz=2"
The returned string is formed using method URI.encode_www_form_component, which converts certain characters:
URI.encode_www_form('f#o': '/', 'b-r': '$', 'b z': '@') # => "f%23o=%2F&b-r=%24&b+z=%40"
When enum is Array-like, each element ele is converted to a field:
-
If
eleis an array of two or more elements, the field is formed from its first two elements (and any additional elements are ignored):Examplename = URI.encode_www_form_component(ele[0], enc) value = URI.encode_www_form_component(ele[1], enc) "#{name}=#{value}"
Examples:
ExampleURI.encode_www_form([%w[foo bar], %w[baz bat bah]]) # => "foo=bar&baz=bat" URI.encode_www_form([['foo', 0], ['bar', :baz, 'bat']]) # => "foo=0&bar=baz"
-
If
eleis an array of one element, the field is formed fromele[0]:ExampleURI.encode_www_form_component(ele[0])
Example:
ExampleURI.encode_www_form([['foo'], [:bar], [0]]) # => "foo&bar&0"
-
Otherwise the field is formed from
ele:ExampleURI.encode_www_form_component(ele)
Example:
ExampleURI.encode_www_form(['foo', :bar, 0]) # => "foo&bar&0"
The elements of an Array-like enum may be mixture:
URI.encode_www_form([['foo', 0], ['bar', 1, 2], ['baz'], :bat]) # => "foo=0&bar=1&baz&bat"
When enum is Hash-like, each key/value pair is converted to one or more fields:
-
If
valueis Array-convertible, each elementeleinvalueis paired withkeyto form a field:Examplename = URI.encode_www_form_component(key, enc) value = URI.encode_www_form_component(ele, enc) "#{name}=#{value}"
Example:
ExampleURI.encode_www_form({foo: [:bar, 1], baz: [:bat, :bam, 2]}) # => "foo=bar&foo=1&baz=bat&baz=bam&baz=2"
-
Otherwise,
keyandvalueare paired to form a field:Examplename = URI.encode_www_form_component(key, enc) value = URI.encode_www_form_component(value, enc) "#{name}=#{value}"
Example:
ExampleURI.encode_www_form({foo: 0, bar: 1, baz: 2}) # => "foo=0&bar=1&baz=2"
The elements of a Hash-like enum may be mixture:
URI.encode_www_form({foo: [0, 1], bar: 2}) # => "foo=0&foo=1&bar=2"