Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Rails I18n strings with full keys

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

config/locales/en.yml

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

config/locales/second.en.yml

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

I want the following output:

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

How do I do this?

like image 788
Russell Silva Avatar asked Aug 16 '13 21:08

Russell Silva


3 Answers

Once loaded into memory it's just a big Hash, which you can format any way you want. to access it you can do this:

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

To get a list of available translations (created by you or maybe by plugins and gems)

I18n.available_locales
like image 91
konung Avatar answered Sep 28 '22 06:09

konung


Nick Gorbikoff's answer was a start but did not emit the output I wanted as described in the question. I ended up writing my own script get_translations to do it, 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)
like image 36
Russell Silva Avatar answered Sep 28 '22 04:09

Russell Silva


Here's a working version of a method you can use to achieve your desired output

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

Usage:

$ data = YAML.load_file('config/locales/second.en.yml')
$ print_tr(data)
=>

en.farewell.polite: "Goodbye"
en.farewell.informal: "Later"
like image 39
Joseph N. Avatar answered Sep 28 '22 04:09

Joseph N.