Sync two YAML files

Is there any plugin for synchronizing two YAML files? For example, file1 has

en:
   key1: "Value1"
   key2: "Value2"
es:
   key1: "EsValue1"

After synchronization, you need to add key2: "Value2" to the second file without disturbing the order and key1 in the second file.

+1
source share
2 answers

You really don't need a plugin for this:

str = <<EOT
en:
  key1: "Value1"
  key2: "Value2"
es:
  key1: "EsValue1"
EOT

require 'yaml'
yaml = YAML::load(str)

(hash['en'].keys - hash['es'].keys).each{ |k| hash['es'][k] = hash['en'][k] }

>> ap hash #=> nil
{
    "en" => {
        "key1" => "Value1",
        "key2" => "Value2"
    },
    "es" => {
        "key1" => "EsValue1",
        "key2" => "Value2"
    }
}

If you have any number of other hashes to process:

(yaml.keys - ['en']).each do |h|
  (yaml['en'].keys - yaml[h].keys).each do |k|
    yaml[h][k] = yaml['en'][k]
  end
end

So, read the YAML file, run the resulting hash through the code, and then write the file again.

+1
source

, , , Ruby 1.9, , . YAML YAML.load_file, - :

merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
es.merge(en, &merger)

YAML.

: http://www.ruby-forum.com/topic/142809#635081

+2

All Articles