Class: Dentaku::FlatHash

Inherits:
Object
  • Object
show all
Defined in:
lib/dentaku/flat_hash.rb

Class Method Summary collapse

Class Method Details

.expand(hash) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/dentaku/flat_hash.rb', line 29

def self.expand(hash)
  hash.each_with_object({}) do |(k, v), r|
    hash_levels = k.to_s.split('.')
    hash_levels = hash_levels.map(&:to_sym) if k.is_a?(Symbol)
    child_hash = hash_levels[0...-1].reduce(r) { |h, n| h[n] ||= {} }
    child_hash[hash_levels.last] = v
  end
end

.flatten_key(segments) ⇒ Object



22
23
24
25
26
27
# File 'lib/dentaku/flat_hash.rb', line 22

def self.flatten_key(segments)
  return segments.first if segments.length == 1
  key = segments.join('.')
  key = key.to_sym if segments.first.is_a?(Symbol)
  key
end

.flatten_keys(hash) ⇒ Object



16
17
18
19
20
# File 'lib/dentaku/flat_hash.rb', line 16

def self.flatten_keys(hash)
  hash.each_with_object({}) do |(k, v), h|
    h[flatten_key(k)] = v
  end
end

.from_hash(h, key = [], acc = {}) ⇒ Object



3
4
5
6
7
# File 'lib/dentaku/flat_hash.rb', line 3

def self.from_hash(h, key = [], acc = {})
  return acc.update(key => h)  unless h.is_a? Hash
  h.each { |k, v| from_hash(v, key + [k], acc) }
  flatten_keys(acc)
end

.from_hash_with_intermediates(h, key = [], acc = {}) ⇒ Object



9
10
11
12
13
14
# File 'lib/dentaku/flat_hash.rb', line 9

def self.from_hash_with_intermediates(h, key = [], acc = {})
  acc.update(key => h) unless key.empty?
  return unless h.is_a? Hash
  h.each { |k, v| from_hash_with_intermediates(v, key + [k], acc) }
  flatten_keys(acc)
end