How to emit YAML in Ruby expanding aliases
Asked Answered
V

2

5

I am looking for a way to emit YAML files avoiding the use of aliases (mostly for simplified human readability). I think extending Psych::Visitors::Emitter or Psych::Visitors::Visitor is the way to go, but I cannot actually find where Ruby decides whether to dump an anchor in full, or reference it with an alias.

I wouldn't even mind if the anchors were used repeatedly (with their &...... references), I just need to expand aliases to the full structures.

I am aware of similar questions being asked in the past, but:

Veto answered 1/7, 2014 at 10:46 Comment(2)
YAML.dump uses YamlTree to serialize your Ruby data to Yaml. The alias handing is done by the inner Registrar class and it simply emits an alias if the object in question has been seen before (based on object_id).Exaltation
If you implement your own Visitor without aliases watch out for circular references!Exaltation
H
2

The only way I've found to do this is to perform a deep clone of the object being dumped to YAML. This is because YAML will identify the anchors and aliases based on their identity, and if you clone or dup them, the new object will be equal, but have a different identity.

There are many ways to perform a deep clone, including library support, or writing your own helper function -- I'll leave that as an exercise for the reader.

Hallucinate answered 16/6, 2016 at 12:32 Comment(0)
T
4

One simple (hacky) approach I used was convert the yaml to json. and then convert it back to YAML. new YAML does not contain aliases/anchors.

require 'json'

jsonObj = oldYaml.to_json
newYaml = YAML.load(jsonObj)
print newYaml.to_yaml
Terenceterencio answered 7/9, 2017 at 20:4 Comment(0)
H
2

The only way I've found to do this is to perform a deep clone of the object being dumped to YAML. This is because YAML will identify the anchors and aliases based on their identity, and if you clone or dup them, the new object will be equal, but have a different identity.

There are many ways to perform a deep clone, including library support, or writing your own helper function -- I'll leave that as an exercise for the reader.

Hallucinate answered 16/6, 2016 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.