Search code examples
ruby-on-railsrubyruby-on-rails-4rails-i18n

How to list all available locale keys in Rails?


My locale file has become unwieldy with a bunch of nested keys. Is there a way to get a list of all available locale keys, or all locale keys from a single locale file?

For eg.

en:
  car:
     honda:
          civic:
               name: 'Civic'
               description: 'Entry Level Sedan'
     ferrari:
          la_ferrari:
               name: 'La Ferrari'
               description: 'Supercar'

This locale should return the list of keys, which in this case is

['en.car.honda.civic.name', 'en.car.honda.civic.description',
'en.ferrari.la_ferrari.name', 'en.car.ferrari.la_ferrari.name.description']

Is there a Rails (I18n) helper to do this? The other way is to iterate over the parsed YAML.


Solution

  • This is a script I've written when I had to deal with this. Working great for me.

    #! /usr/bin/env ruby
    
    require 'yaml'
    
    filename = if ARGV.length == 1
      ARGV[0]
    elsif ARGV.length == 0
      "/path/to/project/config/locales/new.yml"
    end
    
    unless filename
      puts "Usage: flat_print.rb filename"
      exit(1)
    end
    
    hash = YAML.load_file(filename)
    hash = hash[hash.keys.first]
    
    def recurse(obj, current_path = [], &block)
      if obj.is_a?(String)
        path = current_path.join('.')
        yield [path, obj]
      elsif obj.is_a?(Hash)
        obj.each do |k, v|
          recurse(v, current_path + [k], &block)
        end
      end
    end
    
    recurse(hash) do |path, value|
      puts path
    end