Module: Nestful::Helpers

Extended by:
Helpers
Included in:
Helpers
Defined in:
lib/nestful/helpers.rb

Constant Summary collapse

DEFAULT_SEP =

Stolen from Rack:

/[&;] */n
ESCAPE_RE =
/[^a-zA-Z0-9 .~_-]/

Instance Method Summary collapse

Instance Method Details

#camelize(value) ⇒ Object



9
10
11
# File 'lib/nestful/helpers.rb', line 9

def camelize(value)
  value.to_s.split('_').map {|w| w.capitalize }.join
end

#deep_merge(hash, other_hash) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/nestful/helpers.rb', line 13

def deep_merge(hash, other_hash)
  hash.merge(other_hash) do |key, oldval, newval|
    oldval = oldval.to_hash if oldval.respond_to?(:to_hash)
    newval = newval.to_hash if newval.respond_to?(:to_hash)
    oldval.class.to_s == 'Hash' && newval.class.to_s == 'Hash' ? deep_merge(oldval, newval) : newval
  end
end

#escape(s) ⇒ Object



69
70
71
# File 'lib/nestful/helpers.rb', line 69

def escape(s)
  URI.encode_www_form_component(s.to_s)
end

#from_param(qs, d = nil) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/nestful/helpers.rb', line 57

def from_param(qs, d = nil)
  params = {}

  (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
    k, v = p.split('=', 2).map { |s| unescape(s) }

    normalize_params(params, k, v)
  end

  params
end

#to_param(value, prefix = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/nestful/helpers.rb', line 25

def to_param(value, prefix = nil)
  case value
  when Array
    value.map { |v|
      to_param(v, "#{prefix}[]")
    }.join("&")
  when Hash
    value.map { |k, v|
      to_param(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
    }.join("&")
  else
    raise ArgumentError, "value must be a Hash" if prefix.nil?
    "#{prefix}=#{escape(value)}"
  end
end

#to_path(*params) ⇒ Object



5
6
7
# File 'lib/nestful/helpers.rb', line 5

def to_path(*params)
  params.map(&:to_s).reject(&:empty?) * '/'
end

#to_url_param(value, prefix = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/nestful/helpers.rb', line 41

def to_url_param(value, prefix = nil)
  case value
  when Array
    value.map { |v|
      to_url_param(v, "#{prefix}[]")
    }.join("&")
  when Hash
    value.map { |k, v|
      to_url_param(v, prefix ? "#{prefix}[#{uri_escape(k)}]" : uri_escape(k))
    }.join("&")
  else
    raise ArgumentError, "value must be a Hash" if prefix.nil?
    "#{prefix}=#{uri_escape(value)}"
  end
end

#unescape(s, encoding = nil) ⇒ Object



82
83
84
# File 'lib/nestful/helpers.rb', line 82

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

#uri_escape(s) ⇒ Object



75
76
77
78
79
# File 'lib/nestful/helpers.rb', line 75

def uri_escape(s)
  s.to_s.gsub(ESCAPE_RE) {|match|
    '%' + match.unpack('H2' * match.bytesize).join('%').upcase
  }.tr(' ', '+')
end