Module: I18nYamlEditor::Transformation

Included in:
Store
Defined in:
lib/i18n_yaml_editor/transformation.rb

Class Method Summary collapse

Class Method Details

.flatten_hash(hash, namespace = [], tree = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/i18n_yaml_editor/transformation.rb', line 7

def flatten_hash hash, namespace=[], tree={}
  hash.each {|key, value|
    child_ns = namespace.dup << key
    if value.is_a?(Hash)
      flatten_hash value, child_ns, tree
    else
      tree[child_ns.join(".")] = value
    end
  }
  tree
end

.nest_hash(hash) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/i18n_yaml_editor/transformation.rb', line 20

def nest_hash hash
  result = {}
  hash.each {|key, value|
    begin
      sub_result = result
      keys = key.split(".")
      keys.each_with_index {|k, idx|
        if keys.size - 1 == idx
          sub_result[k.to_s] = value
        else
          sub_result = (sub_result[k.to_s] ||= {})
        end
      }
    rescue => e
      raise TransformationError.new("Failed to nest key: #{key.inspect} with value: #{value.inspect}")
    end
  }
  result
end