Class: AlphaCard::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/alpha_card/utils.rb

Overview

Some stolen methods to clear library dependencies.

Constant Summary collapse

DEFAULT_SEP =

Default separators for the query string.

/[&;] */n

Class Method Summary collapse

Class Method Details

.parse_query(query, d = nil) {|unescaper| ... } ⇒ Hash

Parse query string to a Hash by breaking it up at the '&' and ';' characters.

Examples:


query = AlphaCard::Utils.parse_query("param1=value1&params2=")
#=> {"param1"=>"value1", "params2"=>""}

query = AlphaCard::Utils.parse_query("cars[]=Saab&cars[]=Audi")
#=> {"cars[]"=>["Saab", "Audi"]}

Parameters:

  • query (String)

    query string

  • d (String) (defaults to: nil)

    delimiter for the params

Yield Parameters:

  • unescaper

    method, that will unescape the param value

Returns:

  • (Hash)

    query


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/alpha_card/utils.rb', line 59

def parse_query(query, d = nil, &unescaper)
  unescaper ||= method(:unescape)

  params = {}

  (query || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
    next if p.empty?
    k, v = p.split('=', 2).map(&unescaper)

    if cur = params[k]
      if cur.class == Array
        params[k] << v
      else
        params[k] = [cur, v]
      end
    else
      params[k] = v
    end
  end

  params
end

.unescape(s, encoding = Encoding::UTF_8) ⇒ String

Unescapes a URI escaped string with encoding. encoding will be the target encoding of the string returned, and it defaults to UTF-8

Examples:


unescape('Test%20str')
#=> "Test str"

unescape('Test%20str', Encoding::WINDOWS_31J)
#=> "Test str"

Parameters:

  • s (String)

    String to unescape.

  • encoding (Encoding) (defaults to: Encoding::UTF_8)

    Type of Encoding.

Returns:

  • (String)

    URI encoded string

Raises:

  • (ArgumentError)

    if invalid Encoding is passed


35
36
37
# File 'lib/alpha_card/utils.rb', line 35

def unescape(s, encoding = Encoding::UTF_8)
  URI.decode_www_form_component(s, encoding)
end