问题
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:
- Ruby YAML write without aliases remained unanswered
- Is it possible to emit valid YAML with anchors / references disabled using Ruby or Python? gave answer for Python but not for Ruby
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/24508364/how-to-emit-yaml-in-ruby-expanding-aliases