Module: YamlNormalizer::Ext::Namespaced

Defined in:
lib/yaml_normalizer/ext/namespaced.rb

Overview

YamlNormalizer::Ext::Namespaced extends instances of Hash to provide the additional public helper method namespaced. The approach of extending Hash instances avoids monkey-patching a Ruby Core class and using refinements.

Instance Method Summary collapse

Instance Method Details

#namespaced(namespace = [], tree = {}) ⇒ Hash

Transforms a tree-shaped Hash into a flat key-value pair Hash, separating tree levels with a dot. namespaced does not modify the instance of Hash it’s called on.

Examples:

hash = {a: {b: {c: 1}}, b:{x: 2, y: {ok: true}, z: 4}}
hash.extend(YamlNormalizer::Ext::Namespaced)
hash.namespaced
=> {"a.b.c"=>1, "b.x"=>2, "b.y.ok"=>true, "b.z"=>4}

Parameters:

  • namespace (Array) (defaults to: [])

    the namespace cache for the current namespace, used on recursive tree traversal1

  • tree (Hash) (defaults to: {})

    the accumulator object being build while recursive traversing the original tree-shaped Hash

Returns:

  • (Hash)

    flat key-value pair Hash



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/yaml_normalizer/ext/namespaced.rb', line 23

def namespaced(namespace = [], tree = {})
  each do |key, value|
    child_ns = namespace.dup << key
    if value.instance_of?(Hash)
      value.extend(Namespaced).namespaced child_ns, tree
    else
      tree[child_ns.join('.')] = value
    end
  end
  tree
end