Created
June 29, 2015 18:57
-
-
Save lonniev/db374d9d9b461d925e66 to your computer and use it in GitHub Desktop.
Given a nested hash, pretty print a list of corresponding dotted property = value lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'JSON' | |
require 'pp' | |
def hashList( list, value ) | |
head, *tail = list | |
head.sub!( /\[(.+)\]/, '\1' ) | |
case tail | |
when [] | |
" { #{head} => '#{value}' } " | |
else | |
"{ #{head} => #{hashList( tail, value )} }" | |
end | |
end | |
class ::Hash | |
def deep_merge(second) | |
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } | |
self.merge(second, &merger) | |
end | |
end | |
def hashify( properties ) | |
strings = properties.collect { |l| | |
parts = l.partition( '=' ) | |
if parts[1] == '=' | |
key = parts[0] | |
value = parts[2].chomp | |
key.gsub!( /\.?([^\.]+)/, %q(['\1']) ) | |
keys = key.scan( /\['[^']+'\]/ ) | |
hashList( keys, value ) | |
end | |
}.reject{ |s| s.nil? } | |
desireds = strings.collect { |sh| | |
JSON.parse( sh.gsub("'",'"').gsub('=>',':') ) | |
} | |
big = Hash.new() | |
desireds.each { |h| | |
big = big.deep_merge( h ) | |
} | |
pp big | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment