避免在本地化文件中重复

时间:2016-03-15 06:25:17

标签: ruby-on-rails ruby localization yaml

我目前正在一个项目中工作,出于某种原因,每种语言都有两个文件具有几乎相同的内容:

config/locales/en/my_translations.yml
config/locales/en/my_special_translations.yml
config/locales/pt/my_translations.yml
config/locales/pt/my_special_translations.yml

具有相同名称的文件具有相同的内容,已翻译为不同的语言。这里的问题是my_translationsmy_special_translations有很多重复的代码。下面我展示了一个假数据示例,以显示重复和差异的位置:

config/locales/en/my_translations.yml

es:
  animals:
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse
    sad_animals:
      cow: Cow
      elephant: Elephant

config/locales/en/my_special_translations.yml

es:
  special_animals:    # This line is different
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse
    sad_animals:
      cow: Farm cow   # This line is different
      elephant: Elephant

这只是一个例子,但我有几百行的文件,其中只有少数或不同。有没有办法减少或避免文件之间的这种重复?

修改

我使用此代码的方式如下:

animals_scope = special? ? 'special_animals' : 'animals'
animals_hash = I18n.translate(animals_scope, locale: current_locale)
animals_hash.keys.each do|animal_key|
  # Stuff
end

也就是说,对于.yml文件中的每个元素,我正在执行一些操作

1 个答案:

答案 0 :(得分:3)

您可以使用YAML anchors and aliases并仅覆盖不同的值:

es:
  animals: &ANIMALS
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse

    sad_animals:
      cow: Cow
      elephant: Elephant

  special_animals:
    <<: *ANIMALS
    sad_animals:
      cow: Farm cow
相关问题