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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With