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.



6
7
8
# File 'lib/morfo/tools.rb', line 6

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

Instance Attribute Details

#input_hashObject (readonly)

Returns the value of attribute input_hash.



4
5
6
# File 'lib/morfo/tools.rb', line 4

def input_hash
  @input_hash
end

Instance Method Details

#flattenObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/morfo/tools.rb', line 10

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