Ruby: dynamically construct an hash from another -


given yaml file sample values need iterate on , construct 1 editing values throught interactive console steps. code trying.

require 'yaml' require 'awesome_print'  def set_globals   @defaults = yaml.load_file('config.example.yml')   @globals = {}       @defaults.each |k, v|     set_value k, v, []   end end  def set_value k, v, chain   if v['wtf_kind'] && v['wtf_kind'] == 'string'     set_key chain.push(k), 'random' #this should trigger console session   else     set_value v.first.first, v.first.last, chain.push(k)   end end  def set_key chain, v   c = 0   last = {}   while c <= chain.size     if c == chain.size       @globals.store(chain[c], v)     else        @globals.store(chain[c], {})     end     c += 1   end end  set_globals  ap @globals 

config.example.yaml

global:   redmine:     site:        wtf_kind: string       question: redmine server url       default: http://redmineaddress.com      user:        wtf_kind: string       question: redmine username       default: spitzname      password:        wtf_kind: string       question: redmine password       default: changeme 

what is:

{      "global" => {},     "redmine" => {},        "site" => {},           nil => "random" } 

while expect get:

{   "global" => {     "redmine" => {        "site" => "random"      }    } } 

try using simple recursion:

require 'yaml' require 'awesome_print'  def travel(data)   if data['wtf_kind'] == 'string'     'random' #this should trigger console session   else      r = hash.new     data.each |k, v|       r[k] = travel(data[k])     end     r   end end  @data = yaml.load_file('example.yml') ap travel(@data) 

output:

{ "global" => {     "redmine" => {         "site" => "random",         "user" => "random",     "password" => "random"     } } } 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -