Module: DeepSymbolizable::Symbolizers
Instance Method Summary collapse
-
#_recurse_(value, invert, &block) ⇒ Object
handling recursion - any Enumerable elements (except String) is being extended with the module, and then symbolized.
-
#array(ary, invert, &block) ⇒ Object
walking over arrays and symbolizing all nested elements.
-
#hash(hash, invert, &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.
Instance Method Details
#_recurse_(value, invert, &block) ⇒ Object
handling recursion - any Enumerable elements (except String) is being extended with the module, and then symbolized
61 62 63 64 65 66 67 68 |
# File 'lib/deep_symbolize.rb', line 61 def _recurse_(value, invert, &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(invert, &block) end value end |
#array(ary, invert, &block) ⇒ Object
walking over arrays and symbolizing all nested elements
55 56 57 |
# File 'lib/deep_symbolize.rb', line 55 def array(ary, invert, &block) ary.map { |v| _recurse_(v, invert, &block) } end |
#hash(hash, invert, &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
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/deep_symbolize.rb', line 28 def hash(hash, invert, &block) hash.inject({}) do |result, (key, value)| # Recursively deep-symbolize subhashes value = _recurse_(value, invert, &block) # Pre-process the key with a block if it was given key = yield key if block_given? if invert # UN-Symbolize the key s_key = key.to_s rescue key # write it back into the result and return the updated hash result[s_key] = value else # 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 end result end end |