如何在不丢失注释和变量的情况下更新 Rails 语言环境 YAML 文件? [英] How do I update Rails locale YAML file without loosing comments and variables?

查看:32
本文介绍了如何在不丢失注释和变量的情况下更新 Rails 语言环境 YAML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Ruby 脚本来更改 config/locales/*.yml Rails 语言环境文件的内容.这些文件包含许多有用的注释和变量.

I'm building a Ruby script that changes the contents of the config/locales/*.yml Rails locales files. These files contain many useful comments and variables.

通过加载、更新和转储它们,我丢失了这些注释和变量.

By loading, updating, and dumping them, I loose these comments and variables.

如何在保留注释和变量的同时以编程方式更新 YAML 文件?

How do I programatically update the YAML file while preserving comments and variables?

推荐答案

我不认为你可以.

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

这篇关于如何在不丢失注释和变量的情况下更新 Rails 语言环境 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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