0
0
Fork 0

Add and use decode_www_form_component_18

This replaces URI encoded chars back into their original form.
This commit is contained in:
Stormwind 2012-12-22 15:25:35 +01:00
parent bfca378f8f
commit 0e12faff22
1 changed files with 42 additions and 22 deletions

View File

@ -2,7 +2,8 @@ module URI
# Gets a query string and splits it into its key value pairs.
# If URI already supports this functionality (decode_www_form on Ruby 1.9+),
# it will use this. Else ... nothing at the moment.
# it will use this. Else it will run an onw implementation, without any
# encoding functionality.
#
# @param [String] query The query string
# @return [Array] Parsed query
@ -17,6 +18,7 @@ module URI
return self.decode_www_form_18 query
end
# Own implementation of decode_www_form.
# Shall behave almost like the original method, but without any encoding
# stuff.
@ -35,36 +37,54 @@ module URI
query.split(/[&;]/).each do |query_part|
# breakes the string parts at =
key, value = query_part.split('=')
# make an empty string out of value, if it's nil
value = '' if value.nil?
# append the key value pair on the result array
parsed << [key, value]
parsed << [
decode_www_form_component_18(key),
decode_www_form_component_18(value)
]
end
# return result array
return parsed
end
=begin
WFKV_ = '(?:[^%#=;&]*(?:%\h\h[^%#=;&]*)*)'
TBLDECWWWCOMP18_ = {}
def self.decode_www_form(str, enc= nil)
return [] if str.empty?
unless /\A#{WFKV_}=#{WFKV_}(?:[;&]#{WFKV_}=#{WFKV_})*\z/ =~ str
raise ArgumentError,
"invalid data of application/x-www-form-urlencoded (#{str})"
# Own implementation of decode_www_form_component.
# Shall behave almost like the original method, but without any encoding
# stuff.
#
# @param [String] string
# @return [String]
#
def self.decode_www_form_component_18(string)
# Fill table for URI special chars
if TBLDECWWWCOMP18_.empty?
tbl = {}
256.times do |i|
h, l = i>>4, i&15
tbl['%%%X%X' % [h, l]] = i.chr
tbl['%%%x%X' % [h, l]] = i.chr
tbl['%%%X%x' % [h, l]] = i.chr
tbl['%%%x%x' % [h, l]] = i.chr
end
tbl['+'] = ' '
begin
TBLDECWWWCOMP18_.replace(tbl)
TBLDECWWWCOMP18_.freeze
rescue
end
end
ary = []
$&.scan(/([^=;&]+)=([^;&]*)/) do
ary << [
decode_www_form_component($1, enc),
decode_www_form_component($2, enc)
]
end
ary
end
# unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
# raise ArgumentError, "invalid %-encoding (#{str})"
# end
def self.decode_www_form_component(str, enc= nil)
raise ArgumentError, "invalid %-encoding (#{str})" unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
# Replace URI special chars
string.gsub(/\+|%[a-zA-Z0-9]{2}/) do |sub_string|
TBLDECWWWCOMP18_[sub_string]
end
end
=end
end