Class: BabelDiff::HashFlattener

Inherits:
Struct
  • Object
show all
Defined in:
lib/babel_diff/hash_flattener.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#hashObject

Returns the value of attribute hash

Returns:

  • (Object)

    the current value of hash



2
3
4
# File 'lib/babel_diff/hash_flattener.rb', line 2

def hash
  @hash
end

Instance Method Details

#flat_hashObject



3
4
5
# File 'lib/babel_diff/hash_flattener.rb', line 3

def flat_hash
  @_flat_hash ||= {}
end

#flatten(current_hash = hash, keys = []) ⇒ Object



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

def flatten(current_hash = hash, keys = [])
  current_hash.each do |key, value|
    new_keys = keys.dup << key
    if value.is_a? Hash
      flatten(value, new_keys)
    else
      flat_hash[new_keys.join(".")] = value
    end
  end
  flat_hash
end

#unflattenObject



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/babel_diff/hash_flattener.rb', line 19

def unflatten
  {}.tap do |unflattened_hash|
    hash.each do |k,v|
      keys = k.split(".")
      current_hash = unflattened_hash

      keys[0...-1].each { |key| current_hash = current_hash[key] ||= {} }

      current_hash[keys.last] = v
    end
  end
end