Module: DeepSymbolizable::Symbolizers
- Defined in:
- lib/deep_symbolize.rb
Overview
SYMBOLIZERS ———————————-
Used to symbolize hashes
Class Method Summary collapse
-
._recurse_(value, &block) ⇒ Object
——————————————– RECURSE ———————————— ——————————————– Handling recursion - any Enumerable elements (except String) is being extended with the module, and then symbolized.
-
.array(ary, &block) ⇒ Object
——————————————– ARRAY ————————————– ——————————————– Walking over arrays and symbolizing all nested elements.
-
.hash(hash, &block) ⇒ Object
——————————————– HASH ————————————— ——————————————– 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.
Class Method Details
._recurse_(value, &block) ⇒ Object
RECURSE ————————————
Handling recursion - any Enumerable elements (except String) is being extended with the module, and then symbolized
55 56 57 58 59 60 61 62 63 64 |
# File 'lib/deep_symbolize.rb', line 55 def _recurse_(value, &block) if value.is_a?(Enumerable) && !value.is_a?(String) # Support for a use case without extended core Hash unless value.class.include?(DeepSymbolizable) value.extend DeepSymbolizable end value = value.deep_symbolize(&block) end value end |
.array(ary, &block) ⇒ Object
ARRAY ————————————–
Walking over arrays and symbolizing all nested elements
47 48 49 |
# File 'lib/deep_symbolize.rb', line 47 def array(ary, &block) ary.map { |v| _recurse_(v, &block) } end |
.hash(hash, &block) ⇒ Object
HASH —————————————
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
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/deep_symbolize.rb', line 26 def hash(hash, &block) hash.each_with_object({}) do |(key, value), result| # 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 = begin key.to_sym rescue StandardError key end # Write it back into the result and return the updated hash result[sym_key] = value end end |