Module: Summon::Transport::Qstring

Included in:
Headers, Http
Defined in:
lib/summon/transport/qstring.rb

Instance Method Summary collapse

Instance Method Details

#encode_param(k, v, do_urlencode) ⇒ Object



35
36
37
# File 'lib/summon/transport/qstring.rb', line 35

def encode_param(k, v, do_urlencode)
  "#{k.to_s}=#{do_urlencode ? urlencode(v.to_s) : v.to_s}"
end

#from_query_string(qstr) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/summon/transport/qstring.rb', line 39

def from_query_string(qstr)
  qstr ||= ""
  {}.tap do |result|
    for param in qstr.split('&')
      m,k,v = *param.match(/^(.*?)=(.*?)$/)
      if current = result[k]
        result[k] = current.kind_of?(Array) ? current : [current]
        result[k] << urldecode(v)
      else
        result[k] = urldecode(v)
      end
    end
  end
end

#to_query_string(hash, urlencode = true) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/summon/transport/qstring.rb', line 8

def to_query_string(hash, urlencode = true)
  hash.reject {|k,v| v.nil? || v == ''}.inject([]) do |qs,pair|
    qs.tap do
      k,v = pair
      if v.is_a?(Array)
        for el in v
          qs << encode_param(k, el, urlencode)
        end
      else
        qs << encode_param(k, v, urlencode)
      end
    end
  end.reject{|o| o.nil? || o.empty?}.sort.join('&')
end

#urldecode(str) ⇒ Object



31
32
33
# File 'lib/summon/transport/qstring.rb', line 31

def urldecode(str)
  CGI.unescape(str)
end

#urlencode(str) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/summon/transport/qstring.rb', line 23

def urlencode(str)
  if URI.respond_to?(:encode_www_form_component)
    URI.encode_www_form_component str
  else
    str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0].ord) }
  end
end