Sha256: cb1d834c51ad8c568f2bbdc2029650c5eab0a34ad3d8cff419a9135f2e56cd80
Contents?: true
Size: 856 Bytes
Versions: 4
Compression:
Stored size: 856 Bytes
Contents
module Dentaku class FlatHash 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 def self.flatten_keys(hash) hash.each_with_object({}) do |(k, v), h| h[flatten_key(k)] = v end end 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 def self.expand(h) h.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 end end
Version data entries
4 entries across 4 versions & 1 rubygems
Version | Path |
---|---|
dentaku-3.3.0 | lib/dentaku/flat_hash.rb |
dentaku-3.2.1 | lib/dentaku/flat_hash.rb |
dentaku-3.2.0 | lib/dentaku/flat_hash.rb |
dentaku-3.1.0 | lib/dentaku/flat_hash.rb |