How to emit YAML in Ruby expanding aliases

ぐ巨炮叔叔 提交于 2019-12-20 02:29:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!