7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

重複する複数のyamlを一つにマージする

Posted at

RailsのI18nの辞書ファイルをマージするときにハマったので共有します。

sample.ja.yml
ja:
  active_records:
    model:
      model_1:
        name: 名前

のような辞書ファイルをモデルやビュー毎に作成していたのですが、これらを一つのファイルにマージしようとして、

command
cat models.yml views.yml controllers.yml > all.yml

ってやってもうまくマージできません。
yamlのノードを再帰的にマージしてあげる必要があります。で、作ったのがこれ。

merge-yaml.rb
require 'yaml'

merged_yaml = {}

def merge_yaml(yaml1, yaml2)
  yaml2.each do |key, value|
    if value.class == Hash && yaml1.key?(key)
      yaml1[key] = merge_yaml(yaml1[key], value)
    else
      yaml1[key] = value
    end
  end
  return yaml1
end
    
ARGV.each do |file|
  yaml = YAML.load_file(file)
  merged_yaml = merge_yaml(merged_yaml, yaml)
end

puts merged_yaml.to_yaml

コマンドラインにマージしたいyamlファイルを列挙してあげればオッケー。

command
ruby merge-yaml.rb views/ja.yml controllers/ja.yml models/ja.yml
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?