How to retrieve all translations from yml files in Rails I18n

怎甘沉沦 提交于 2019-11-29 23:50:53

You got to call a private method on the backend. This is how you get access:

translations = I18n.backend.send(:translations)
translations[:en][:test_string] # => "testing this"

As per 8xx8's comment, a simpler version of:

I18n.t(:foo)
I18n.backend.send(:translations)[:en][:test_string]

is

I18n.t(".")[:test_string]

This mitigates having to both preload the translations or specify the locale.

If you are using I18n::Fallbacks unfortunately you can't use I18n.t('.') as it just returns the contents current locale (eg. 'en-GB') and nothing from any of the fallback locales (eg 'en'). To get round this you can iterate over the fallbacks and use deep_merge! to combine them.

module I18n
  class << self
    def all
      fallbacks[I18n.locale].reverse.reduce({}) do |translations, fallback|
        translations.deep_merge!(backend.translate(fallback, '.'))
      end
    end
  end
end

The default I18n backend is I18n::Backend::Simple, which does not expose the translations to you. (I18.backend.translations is a protected method.)

This isn't generally a good idea, but if you really need this info and can't parse the file, you can extend the backend class.

class I18n::Backend::Simple
  def translations_store
    translations
  end
end

You can then call I18n.backend.translations_store to get the parsed translations. You probably shouldn't rely on this as a long term strategy, but it gets you the information you need right now.

If you're doing this in a rake task, remember to include the enviroment, or otherwise it will not load your own locales which lives under config/locales/

require "./config/environment.rb" # Do not forget this

namespace :i18n do
  desc "Import I18n to I18n_active_record"
  task :setup do
    I18n.t(:foo)
    translations = I18n.backend.send(:translations)
  end
end

For the people wandering into this old question, there is a solution that does not require calling protected methods. Change your yml file as follows:

nl: &all

  ... translations here ...

  all:
    <<: *all

Now you can simply extract all translations using I18n.t("all"), which has the benefit of automatically initializing and reloading the translations in development mode (something which doesn't happen if you call the protected methods.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!