开发者

Synchronize two YAML files

Is there any plugin to synchronize two开发者_如何学编程 YAML files ? For example file1 has

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

After synchronizing it needs to add key2: "Value2" in the second file without disturbing the order and the key1 in the second file.


I'm not sure if this will keep the order as you want, but if you use Ruby 1.9 it's pretty likely as it's using sorted hashes. You could read contents of the YAML files into hashes using YAML.load_file and then do something like this:

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

and then dump es hash to the YAML file again.

This solution for recursive merging was suggested here: http://www.ruby-forum.com/topic/142809#635081


You don't really need a plugin to do it:

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 an arbitrary 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, then write the file again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜