Module: URI

Defined in:
lib/patches/uri.rb

Constant Summary collapse

TBLDECWWWCOMP_ =
{}

Class Method Summary collapse

Class Method Details

.decode_www_form(query, _encoding = nil) ⇒ Array

Own implementation of decode_www_form. Shall behave almost like the original method, but without any encoding stuff.

Parameters:

  • query (String)

    The query string

  • _encoding (String) (defaults to: nil)

    Unused, only for compatibility

Returns:

  • (Array)

    Parsed query



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/patches/uri.rb', line 11

def self.decode_www_form(query, _encoding = nil)
  return [] if query.empty?

  unless query.match /^[^#=;&]*=[^#=;&]*([;&][^#=;&]*=[^#=;&]*)*$/
    raise ArgumentError,
      "invalid data of application/x-www-form-urlencoded (#{query})"
  end
  parsed = []
  # breakes the string at & and ;
  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 << [
      decode_www_form_component(key),
      decode_www_form_component(value)
    ]
  end
  # return result array
  return parsed
end

.decode_www_form_component(string, _encoding = nil) ⇒ String

Own implementation of decode_www_form_component. Shall behave almost like the original method, but without any encoding stuff.

Parameters:

  • string (String)
  • _encoding (String) (defaults to: nil)

    Unused, only for compatibility

Returns:

  • (String)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/patches/uri.rb', line 46

def self.decode_www_form_component(string, _encoding = nil) 
  # Fill table for URI special chars
  if TBLDECWWWCOMP_.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
      TBLDECWWWCOMP_.replace(tbl)
      TBLDECWWWCOMP_.freeze
    rescue
    end
  end
  # unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
  #   raise ArgumentError, "invalid %-encoding (#{str})"
  # end

  # Replace URI special chars
  string.gsub(/\+|%[a-zA-Z0-9]{2}/) do |sub_string|
    TBLDECWWWCOMP_[sub_string]
  end
end