Module: Delighted::Utils

Defined in:
lib/delighted/utils.rb

Class Method Summary collapse

Class Method Details

.eigenclass(object) ⇒ Object


3
4
5
# File 'lib/delighted/utils.rb', line 3

def self.eigenclass(object)
  class << object; self; end
end

.hash_without_key(hash, key) ⇒ Object


7
8
9
# File 'lib/delighted/utils.rb', line 7

def self.hash_without_key(hash, key)
  hash.reject { |k,v| k == key }.inject({}) { |memo,(k,v)| memo[k] = v; memo }
end

.serialize_values(object) ⇒ Object


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/delighted/utils.rb', line 42

def self.serialize_values(object)
  case object
  when Time, Date
    object.to_i
  when Hash
    object.inject({}) { |memo,(k,v)|
      memo[k] = serialize_values(v)
      memo
    }
  when Array, Set
    object.map { |v| serialize_values(v) }
  else
    object
  end
end

.symbolize_keys(object) ⇒ Object


28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/delighted/utils.rb', line 28

def self.symbolize_keys(object)
  case object
  when Hash
    object.inject({}) { |memo,(k,v)|
      memo[(k.to_sym rescue k)] = Hash === v ? symbolize_keys(v) : v
      memo
    }
  when Array
    object.map { |v| symbolize_keys(v) }
  else
    object
  end
end

.to_query(hash_or_array, namespace = nil) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/delighted/utils.rb', line 11

def self.to_query(hash_or_array, namespace = nil)
  hash_or_array.map { |object|
    k, v = case hash_or_array
    when Hash then object
    when Array then [nil, object]
    else raise ArgumentError, "must pass Hash or Array"
    end

    namespaced_k = namespace ? "#{namespace}[#{k}]" : k

    case v
    when Hash, Array then to_query(v, namespaced_k)
    else "#{CGI.escape(namespaced_k.to_s)}=#{CGI.escape(v.to_s)}"
    end
  }.join("&")
end