用全键列出Rails I18n字符串

Rus*_*lva 5 yaml ruby-on-rails internationalization

我希望能够生成所有I18n键的完整列表以及包含完整键的语言环境的值。换句话说,如果我有这些文件:

config/locales/en.yml

en:
  greeting:
    polite: "Good evening"
    informal: "What's up?"
Run Code Online (Sandbox Code Playgroud)

config/locales/second.en.yml

en:
  farewell:
    polite: "Goodbye"
    informal: "Later"
Run Code Online (Sandbox Code Playgroud)

我想要以下输出:

greeting.polite: "Good evening"
greeting.informal: "What's up?"
farewell.polite: "Goodbye"
farewell.informal: "Later"
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

kon*_*ung 7

一旦加载到内存中,它只是一个大哈希,您可以按照您想要的方式对其进行格式化。要访问它,您可以执行以下操作:

I18n.backend.send(:translations)[:en]
Run Code Online (Sandbox Code Playgroud)

获取可用翻译的列表(由您创建或可能由插件和 gems 创建)

I18n.available_locales
Run Code Online (Sandbox Code Playgroud)


Rus*_*lva 5

尼克·戈尔比科夫(Nick Gorbikoff)的回答只是一个开始,但并未如问题中所述发出我想要的输出。我最终在下面编写了自己的脚本get_translations来做到这一点。

#!/usr/bin/env ruby

require 'pp'
require './config/environment.rb'

def print_translations(prefix, x)
  if x.is_a? Hash
    if (not prefix.empty?)
        prefix += "."
    end
    x.each {|key, value|
      print_translations(prefix + key.to_s, value)
    }
  else
      print prefix + ": "
      PP.singleline_pp x
      puts ""
  end
end

I18n.translate(:foo)
translations_hash = I18n.backend.send(:translations)
print_translations("", translations_hash)
Run Code Online (Sandbox Code Playgroud)