Class: BetterTranslate::Utils::HashFlattener
- Inherits:
-
Object
- Object
- BetterTranslate::Utils::HashFlattener
- Defined in:
- lib/better_translate/utils/hash_flattener.rb
Overview
Utilities for flattening and unflattening nested hashes
Used to convert nested YAML structures to flat key-value pairs and back again.
Class Method Summary collapse
-
.flatten(hash, parent_key = "", separator = ".") ⇒ Hash
Flatten a nested hash to dot-notation keys.
-
.unflatten(hash, separator = ".") ⇒ Hash
Unflatten a hash with dot-notation keys to nested structure.
Class Method Details
.flatten(hash, parent_key = "", separator = ".") ⇒ Hash
Flatten a nested hash to dot-notation keys
Recursively converts nested hashes into a single-level hash with keys joined by a separator (default: ".").
49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/better_translate/utils/hash_flattener.rb', line 49 def self.flatten(hash, parent_key = "", separator = ".") initial_hash = {} # : Hash[String, untyped] hash.each_with_object(initial_hash) do |(key, value), result| new_key = parent_key.empty? ? key.to_s : "#{parent_key}#{separator}#{key}" if value.is_a?(Hash) result.merge!(flatten(value, new_key, separator)) else result[new_key] = value end end end |
.unflatten(hash, separator = ".") ⇒ Hash
Unflatten a hash with dot-notation keys to nested structure
Converts a flat hash with delimited keys back into a nested hash structure.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/better_translate/utils/hash_flattener.rb', line 87 def self.unflatten(hash, separator = ".") initial_hash = {} # : Hash[String, untyped] hash.each_with_object(initial_hash) do |(key, value), result| keys = key.split(separator) last_key = keys.pop # Build nested structure nested = keys.reduce(result) do |memo, k| memo[k] ||= {} memo[k] end nested[last_key] = value if last_key end end |