Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update Rails locale YAML file without loosing comments and variables?

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?

like image 249
brauliobo Avatar asked May 05 '13 23:05

brauliobo


1 Answers

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
like image 178
the Tin Man Avatar answered Nov 18 '22 20:11

the Tin Man