且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不丢失注释和变量的情况下更新 Rails 语言环境 YAML 文件?

更新时间:2023-09-20 14:20:52

我不认为你可以.

YAML 会忽略数据文件中的注释,但不会解析它们,因此在加载文件时将它们丢弃.加载文件后,它们就消失了.

YAML ignores comments in a data file, but it doesn't parse them, so they are thrown away as the file is loaded. Once the file is loaded they're gone.

我能想到的做你想做的唯一方法是在 YAML 之外打开文件,然后编写注释,然后编写使用 to_yaml 创建的 YAML 内容.类似的东西:

The only way to do what you want that I can think of, is to open the file outside of YAML, then write the comments, then write the YAML content created using to_yaml. Something like:

require 'yaml'

data = {
  'foo' => 'bar',
}

File.open('data.yaml', 'w') do |fo|
  fo.puts "# Don't mess with this."
  fo.puts data.to_yaml
end

创建:

# Don't mess with this.
---
foo: bar