3

I need to generate this yaml programmatically in Rails:

foo: &foo
  x: 1
  y: 2

bar:
  <<: *foo
  z: 3

which when it's parsed should give this hash:

output = {
    :foo => {
        :x => 1,
        :y => 2
    },
    :bar => {
        :x => 1,
        :y => 2,
        :z => 3
    }
}

Obviously output.to_yaml gives the expanded syntax. Is there any way to output the yml syntax with anchor and nodes programmatically.

Fabio
  • 18,856
  • 9
  • 82
  • 114

1 Answers1

0

I had a similar feature where i read from an initializer many YAML files and appended to a global variable. it is something like this:

APP = Hash.new
Dir.glob("#{Rails.root}/config/data/*.yml").each do |file|
  fdata = File.open(file).read
  APP.merge!(YAML::load(ERB.new(fdata).result(binding)).symbolize_keys!)
end

I should know more about your problem to write a more specific solution.

The main point is the YAML::load method, which reads de yaml formated text and outputs a hash. the ERB is because Yaml files could contain erb tags which should be interpreted. It could or could not be needed. symbolize_keys! is for accessing with [:symbols] and not ["strings"] to keys.

matreyes
  • 18
  • 1
  • 6