Module: Castle::Utils::DeepSymbolizeKeys

Defined in:
lib/castle/utils/deep_symbolize_keys.rb

Class Method Summary collapse

Class Method Details

.call(object, &block) ⇒ Object

Returns a new hash with all keys converted to symbols, as long as they respond to to_sym. This includes the keys from the root hash and from all nested hashes and arrays.

hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }

Castle::Hash.deep_symbolize_keys(hash)
# => {:person=>{:name=>"Rob", :age=>"28"}}


15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/castle/utils/deep_symbolize_keys.rb', line 15

def call(object, &block)
  case object
  when Hash
    object.each_with_object({}) do |(key, value), result|
      result[key.to_sym] = Castle::Utils::DeepSymbolizeKeys.call(value, &block)
    end
  when Array
    object.map { |e| Castle::Utils::DeepSymbolizeKeys.call(e, &block) }
  else
    object
  end
end

.call!(object, &block) ⇒ Object



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

def call!(object, &block)
  case object
  when Hash
    object.each_key do |key|
      value = object.delete(key)
      object[key.to_sym] = Castle::Utils::DeepSymbolizeKeys.call!(value, &block)
    end
    object
  when Array
    object.map! { |e| Castle::Utils::DeepSymbolizeKeys.call!(e, &block) }
  else
    object
  end
end