Frigo
Frigo

Reputation: 374

How to emit YAML in Ruby expanding aliases

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:

Upvotes: 5

Views: 2092

Answers (2)

chetan pawar
chetan pawar

Reputation: 485

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

Upvotes: 4

Grundlefleck
Grundlefleck

Reputation: 129277

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.

Upvotes: 2

Related Questions