Read and write YAML files without destroying anchors and aliases?

Viewed 7331

I need to open a YAML file with aliases used inside it:

defaults: &defaults
  foo: bar
  zip: button

node:
  <<: *defaults
  foo: other

This obviously expands out to an equivalent YAML document of:

defaults:
  foo: bar
  zip: button

node:
  foo: other
  zip: button

Which YAML::load reads it as.

I need to set new keys in this YAML document and then write it back out to disk, preserving the original structure as much as possible.

I have looked at YAML::Store, but this completely destroys the aliases and anchors.

Is there anything available that could something along the lines of:

thing = Thing.load("config.yml")
thing[:node][:foo] = "yet another"

Saving the document back as:

defaults: &defaults
  foo: bar
  zip: button

node:
  <<: *defaults
  foo: yet another

?

I opted to use YAML for this due to the fact it handles this aliasing well, but writing YAML that contains aliases appears to be a bit of a bleak-looking playing field in reality.

3 Answers
Related