How do I update Rails locale YAML file without loo

2019-02-13 18:07发布

问题:

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.

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

回答1:

I don't think you can.

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.

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

Which creates:

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