Class: YamlConvertor::Convertor
- Inherits:
-
Object
- Object
- YamlConvertor::Convertor
- Defined in:
- lib/yaml_convertor.rb
Instance Method Summary collapse
Instance Method Details
#build(flat_hash) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/yaml_convertor.rb', line 26 def build(flat_hash) # create a hash where every key's value is an empty hash # hash[key] <- creates a key and its value will be {} hash = Hash.new{ |h, k| h[k] = Hash.new(&h.default_proc) } flat_hash.each_pair do |key, value| tmp = hash arr_keys = key.split('.') arr_keys.each do |item| if item.eql?(arr_keys.last) tmp[item] = value else tmp = tmp[item] #creates key end end end hash end |
#flatten(nested_hash, keyname = '') ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/yaml_convertor.rb', line 14 def flatten(nested_hash, keyname = '') hash = {} nested_hash.each_pair do |key, value| if value.is_a?(Hash) name = keyname.empty? ? "#{key}" : "#{keyname}.#{key}" hash.merge!(flatten(value, name)) else hash["#{keyname}.#{key}"] = value end end hash end |