Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails i18n how to get all values for a certain key?

In Rails i18n, how to get all values for a certain key using the following:

translations = I18n.backend.send(:translations)

get all the keys

I need to be able to get a certain section for example only return everything under "home"

en:
  home:
    test: test
like image 843
Rubytastic Avatar asked Feb 01 '13 12:02

Rubytastic


2 Answers

The return value of I18n.backend.send(:translations) is just a hash, so you can access a subset just by passing in the appropriate keys.

e.g. if you have:

en:
  foo:
    bar:
      some_term: "a translation"
      some_other_term: "another translation"   

Then you can get the the subset of the hash under bar with:

I18n.backend.send(:translations)[:en][:foo][:bar]
#=> { :some_term=>"a translation", :some_other_term => "another translation"}
like image 196
Chris Salzberg Avatar answered Sep 25 '22 19:09

Chris Salzberg


The default I18n backend is I18n::Backend::Simple, which does not expose the translations to you. (I18n.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.

like image 35
My God Avatar answered Sep 26 '22 19:09

My God