Method: Escape.html_form
- Defined in:
- lib/escape.rb
.html_form(pairs, sep = '&') ⇒ Object
Escape.html_form composes HTML form key-value pairs as a x-www-form-urlencoded encoded string.
Escape.html_form takes an array of pair of strings or an hash from string to string.
Escape.html_form([["a","b"], ["c","d"]]) #=> "a=b&c=d"
Escape.html_form({"a"=>"b", "c"=>"d"}) #=> "a=b&c=d"
In the array form, it is possible to use same key more than once. (It is required for a HTML form which contains checkboxes and select element with multiple attribute.)
Escape.html_form([["k","1"], ["k","2"]]) #=> "k=1&k=2"
If the strings contains characters which must be escaped in x-www-form-urlencoded, they are escaped using %-encoding.
Escape.html_form([["k=","&;="]]) #=> "k%3D=%26%3B%3D"
The separator can be specified by the optional second argument.
Escape.html_form([["a","b"], ["c","d"]], ";") #=> "a=b;c=d"
See HTML 4.01 for details.
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/escape.rb', line 164 def html_form(pairs, sep='&') r = '' first = true pairs.each {|k, v| # query-chars - pct-encoded - x-www-form-urlencoded-delimiters = # unreserved / "!" / "$" / "'" / "(" / ")" / "*" / "," / ":" / "@" / "/" / "?" # query-char - pct-encoded = unreserved / sub-delims / ":" / "@" / "/" / "?" # query-char = pchar / "/" / "?" = unreserved / pct-encoded / sub-delims / ":" / "@" / "/" / "?" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" # x-www-form-urlencoded-delimiters = "&" / "+" / ";" / "=" r << sep if !first first = false k.each_byte {|byte| ch = byte.chr if %r{[^0-9A-Za-z\-\._~:/?@!\$'()*,]}n =~ ch r << "%" << ch.unpack("H2")[0].upcase else r << ch end } r << '=' v.each_byte {|byte| ch = byte.chr if %r{[^0-9A-Za-z\-\._~:/?@!\$'()*,]}n =~ ch r << "%" << ch.unpack("H2")[0].upcase else r << ch end } } r end |