0

Given a yaml file with sample values I need to iterate over it and construct another one editing some values throught interactive console steps. This is the code I was trying.

require 'yaml'
require 'awesome_print'

def set_globals
  @defaults = YAML.load_file('config.example.yml')
  @globals = {}    
  @defaults.each do |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 the 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 I get is:

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

while I expect to get:

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

1 Answer 1

1

Try using simple recursion:

require 'yaml'
require 'awesome_print'

def travel(data)
  if data['wtf_kind'] == 'string'
    'random' #this should trigger the console session
  else 
    r = Hash.new
    data.each do |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"
    }
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.