2

我有 2 个语言环境文件en.ymlpt.yml。有些键只存在于pt.yml和其他键只存在于en.yml

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

示例输出:

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

i18n-tasks missingObs:任务以外的东西 。

4

2 回答 2

4

我发现这个解决方案很完美。它来自 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
于 2017-12-05T20:04:10.013 回答
1

这会做到:

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

于 2016-11-07T13:28:15.627 回答