Module: Padrino::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
padrino-support/lib/padrino-support/utils.rb

Instance Method Summary collapse

Instance Method Details

#build_uri_query(object, namespace = nil) ⇒ Object

Builds an URI query from a Hash or any Object.

Examples (~ marks here that output is actually escaped by CGI):

Utils.build_uri_query(:a => 1, :b => 2)           #=> "a=1&b=2"
Utils.build_uri_query(:a => [1, 2])               #=> ~"a[]=1&a[]=2"
Utils.build_uri_query([1, 2], 'namespace')        #=> ~"namespace[]=1&namespace[]=2"
Utils.build_uri_query(:a => { :d => 2 }, :b => 3) #=> ~"a[d]=2&b=3"


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'padrino-support/lib/padrino-support/utils.rb', line 17

def build_uri_query(object, namespace = nil)
  case object
  when Hash
    object.map do |key, value|
      next if value == {} || value == []
      build_uri_query(value, namespace ? "#{namespace}[#{key}]" : key)
    end.compact.join('&')
  when Array
    fail ArgumentError, 'namespace is missing' unless namespace
    (object.empty? ? [''] : object).map do |value|
      build_uri_query(value, "#{namespace}[]")
    end.join('&')
  else
    fail ArgumentError, 'namespace is missing' unless namespace
    "#{CGI.escape(namespace.to_s)}=#{CGI.escape(object.to_s)}"
  end
end

#deep_dup(object) ⇒ Object

Recursively duplicates the passed object.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'padrino-support/lib/padrino-support/utils.rb', line 38

def deep_dup(object)
  case object
  when Array
    object.map{ |value| deep_dup(value) }
  when Hash
    object.each_with_object(object.dup.clear) do |(key, value), new_hash|
      new_hash[deep_dup(key)] = deep_dup(value)
    end
  when NilClass, FalseClass, TrueClass, Symbol, Numeric, Method
    object
  else
    begin
      object.dup
    rescue TypeError
      object
    end
  end
end

#symbolize_keys(hash) ⇒ Object

Returns a Hash with keys turned into symbols.



60
61
62
63
64
65
66
# File 'padrino-support/lib/padrino-support/utils.rb', line 60

def symbolize_keys(hash)
  result = hash.class.new
  hash.each_key do |key|
    result[(key.to_sym rescue key)] = hash[key]
  end
  result
end