incutonez
incutonez

Reputation: 3329

YAML: Store array as variable

I'm just starting to learn YAML, and I'm not really finding a best practice for something that I'm trying to accomplish. Basically, I have an array of objects in my YAML file, and for production, I'd like to add 1 more entry to this array. So I basically want something like this (it's pseudo code because I know it's not valid YAML):

development:
  array: &ARRAY
  - name: item1
    value: value1
  - name: item2
    value: value2

production:
  <<: *ARRAY
  array:
  - name: item3
    value: value3

Currently, I'm parsing my YAML files with Ruby, so I decided to handle this logic in Ruby. I'm doing something like this:

yaml_contents = YAML::load(yaml_string)
prod_values = yaml_contents['production']
prod_values['array'].push({:name => 'item3', :value => 'value3'})

However, that can make my loading script very hairy. Is there a better way of designing this?

I believe this question is related.

Upvotes: 2

Views: 12903

Answers (1)

matt
matt

Reputation: 79813

The << syntax is for merging maps (i.e. Hashes), not sequences. You could do something like this:

development: &ARRAY
  - name: item1
    value: value1
  - name: item2
    value: value2

production:
  - *ARRAY
  - name: item3
    value: value3

When you load this the production array will have a nested array, so you would need to use flatten:

yaml_contents = YAML::load(yaml_string)
prod_values = yaml_contents['production'].flatten

If your actual data could involve nested hashes and you only want to flatten any arrays that appear as aliases in the Yaml you could write your own Psych visitor (probably a sub class of Psych::Visitors::ToRuby) and merge them in as you create the object graph, but I suspect simply calling flatten will be enough in this case.

Upvotes: 2

Related Questions