Module: DeepSymbolizable::Symbolizers

Extended by:
Symbolizers
Included in:
Symbolizers
Defined in:
lib/dorothy2/deep_symbolize.rb

Instance Method Summary collapse

Instance Method Details

#_recurse_(value, &block) ⇒ Object

handling recursion - any Enumerable elements (except String) is being extended with the module, and then symbolized



52
53
54
55
56
57
58
59
# File 'lib/dorothy2/deep_symbolize.rb', line 52

def _recurse_(value, &block)
  if value.is_a?(Enumerable) && !value.is_a?(String)
    # support for a use case without extended core Hash
    value.extend DeepSymbolizable unless value.class.include?(DeepSymbolizable)
    value = value.deep_symbolize(&block)
  end
  value
end

#array(ary, &block) ⇒ Object

walking over arrays and symbolizing all nested elements



46
47
48
# File 'lib/dorothy2/deep_symbolize.rb', line 46

def array(ary, &block)
  ary.map { |v| _recurse_(v, &block) }
end

#hash(hash, &block) ⇒ Object

the primary method - symbolizes keys of the given hash, preprocessing them with a block if one was given, and recursively going into all nested enumerables



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dorothy2/deep_symbolize.rb', line 29

def hash(hash, &block)
  hash.inject({}) do |result, (key, value)|
    # Recursively deep-symbolize subhashes
    value = _recurse_(value, &block)

    # Pre-process the key with a block if it was given
    key = yield key if block_given?
    # Symbolize the key string if it responds to to_sym
    sym_key = key.to_sym rescue key

    # write it back into the result and return the updated hash
    result[sym_key] = value
    result
  end
end