Class: Morfo::Tools::FlattenHashKeys

Inherits:
Object
  • Object
show all
Defined in:
lib/morfo/tools.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_hash) ⇒ FlattenHashKeys

Returns a new instance of FlattenHashKeys.



23
24
25
# File 'lib/morfo/tools.rb', line 23

def initialize(input_hash)
  @input_hash = input_hash.dup.freeze
end

Instance Attribute Details

#input_hashObject (readonly)

Returns the value of attribute input_hash.



21
22
23
# File 'lib/morfo/tools.rb', line 21

def input_hash
  @input_hash
end

Instance Method Details

#flattenObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/morfo/tools.rb', line 27

def flatten
  input_hash.inject({}) do |result_hash, (key, value)|
    inner_hash = false
    if value.is_a?(::Hash)
      inner_hash = true
      value.each do |inner_key, inner_value|
        if inner_value.is_a?(::Hash)
          inner_hash = true
        end
        result_hash.merge!("#{key}.#{inner_key}".to_sym => inner_value)
      end
    else
      result_hash.merge!(key.to_sym => value)
    end

    if inner_hash
      FlattenHashKeys.new(result_hash).flatten
    else
      result_hash
    end
  end
end