Rails - 查找不同语言环境之间缺少的键(.yml文件)

时间:2015-01-28 14:33:47

标签: ruby-on-rails locale yaml routines

我有2个区域设置文件 en.yml pt.yml 。有些键只存在于 pt.yml 上,而其他键仅存在于 en.yml

是否有方法或例程列出所有这些键? (只是比较两个文件)

示例输出:

en.activerecord.attributes.person.hand
pt.activerecord.models.bird

Obs:i18n-tasks missing任务以外的其他内容。

2 个答案:

答案 0 :(得分:1)

我觉得这个解决方案很完美。它来自Kisko Labs的博客文章。参考文献如下:http://blog.kiskolabs.com/post/908453942/comparing-rails-locale-files-for-missing

LOCALE_1 = "~/Code/project/config/locales/fi.yml"
LOCALE_2 = "~/Code/project/config/locales/en.yml"

require 'yaml'

def flatten_keys(hash, prefix="")
  keys = []
  hash.keys.each do |key|
    if hash[key].is_a? Hash
      current_prefix = prefix + "#{key}."
      keys << flatten_keys(hash[key], current_prefix)
    else
      keys << "#{prefix}#{key}"
    end
  end
  prefix == "" ? keys.flatten : keys
end

def compare(locale_1, locale_2)
  yaml_1 = YAML.load(File.open(File.expand_path(locale_1)))
  yaml_2 = YAML.load(File.open(File.expand_path(locale_2)))

  keys_1 = flatten_keys(yaml_1[yaml_1.keys.first])
  keys_2 = flatten_keys(yaml_2[yaml_2.keys.first])

  missing = keys_2 - keys_1
  file = locale_1.split('/').last
  if missing.any?
    puts "Missing from #{file}:"
    missing.each { |key| puts "  - #{key}" }
  else
    puts "Nothing missing from #{file}."
  end
end

答案 1 :(得分:0)

这样就可以了:

require 'set'
require 'yaml'

files = ['en.yml', 'pt.yml']

p files.map {| file_path| YAML.load(File.read(file_path))}
  .map {|object| Set.new(object.keys) }
  .reduce(:^)

文档:YAMLSet