Ruby on rails Rails-查找不同地区(.yml文件)之间缺少的键

Ruby on rails Rails-查找不同地区(.yml文件)之间缺少的键,ruby-on-rails,locale,yaml,routines,Ruby On Rails,Locale,Yaml,Routines,我有两个语言环境文件en.yml和pt.yml。有些键只存在于pt.yml上,而其他键只存在于en.yml 是否有列出所有这些键的方法或例程?(只是比较两个文件) 示例输出: en.activerecord.attributes.person.hand pt.activerecord.models.bird Obs:i18n任务以外的其他任务缺少任务。这样做: require 'set' require 'yaml' files = ['en.yml', 'pt.yml'] p files

我有两个语言环境文件en.ymlpt.yml。有些键只存在于pt.yml上,而其他键只存在于en.yml

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

示例输出:

en.activerecord.attributes.person.hand
pt.activerecord.models.bird
Obs:i18n任务以外的其他任务缺少任务。

这样做:

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(:^)

医生:而且我发现这个解决方案非常有效。这是Kisko实验室的一篇博文。参考资料如下:

LOCALE\u 1=“~/code/project/config/locales/fi.yml”
LOCALE_2=“~/Code/project/config/locales/en.yml”
需要“yaml”
def展平_键(散列,前缀=”)
键=[]
hash.key.each do| key|
if hash[key]。是否为a?搞砸
当前_前缀=前缀+“#{key}”
钥匙
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