如何在 Ruby 扩展别名中发出 YAML [英] How to emit YAML in Ruby expanding aliases

查看:13
本文介绍了如何在 Ruby 扩展别名中发出 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种生成 YAML 文件的方法,避免使用别名(主要是为了简化人类可读性).我认为扩展 Psych::Visitors::EmitterPsych::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 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

推荐答案

我发现这样做的唯一方法是对转储到 YAML 的对象执行深度克隆.这是因为 YAML 将根据它们的身份识别锚点和别名,如果你 clonedup 它们,新对象将是相同的,但具有不同的身份.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆