Rails I18n Full Key String List

I would like to be able to generate a complete list of all I18n keys and values ​​for the locale, including full keys. In other words, if I have these files:

config/locales/en.yml

 en: greeting: polite: "Good evening" informal: "What up?" 

config/locales/second.en.yml

 en: farewell: polite: "Goodbye" informal: "Later" 

I need the following output:

 greeting.polite: "Good evening" greeting.informal: "What up?" farewell.polite: "Goodbye" farewell.informal: "Later" 

How to do it?

+4
source share
3 answers

Nick Gorbikov’s answer was the beginning, but did not produce the result that I wanted, as described in the question. In the end, I wrote my own get_translations script to do this below.

 #!/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) 
+4
source

Once loaded into memory, it's just a big hash that you can format as you want. to access it you can do this:

 I18n.backend.send(:translations)[:en] 

Get a list of available translations (created by you or possibly plugins and gems)

 I18n.available_locales 
+3
source

Here is a working version of the method that you can use to achieve the desired result.

 def print_tr(data,prefix="") if data.kind_of?(Hash) data.each do |key,value| print_tr(value, prefix.empty? ? key : "#{prefix}.#{key}") end else puts "#{prefix}: #{data}" end end 

Using:

 $ data = YAML.load_file('config/locales/second.en.yml') $ print_tr(data) => en.farewell.polite: "Goodbye" en.farewell.informal: "Later" 
0
source

Source: https://habr.com/ru/post/1497503/


All Articles