问题描述
我正在寻找一种生成 YAML 文件的方法,避免使用别名(主要是为了简化人类可读性).我认为扩展 Psych::Visitors::Emitter
或Psych::Visitors::Visitor
是要走的路,但我实际上无法找到 Ruby 决定是完全转储锚点还是使用别名引用它.
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
orPsych::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 写入无别名仍未得到答复
- 有可能吗使用 Ruby 或 Python 在禁用锚点/引用的情况下发出有效的 YAML? 给出了 Python 的答案,但没有给出 Ruby 的答案
- 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
推荐答案
我发现这样做的唯一方法是对转储到 YAML 的对象执行深度克隆.这是因为 YAML 将根据它们的身份识别锚点和别名,如果你 clone
或 dup
它们,新对象将是相同的,但具有不同的身份.
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.
这篇关于如何在 Ruby 扩展别名中发出 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!