How do I internationalize / localize my rails plugin?

I wrote a validates_word_count plugin . I would like to save the error messages in a YAML file so that they can be easily translated.

My plugin layout is as follows:

validates_word_count/
  init.rb
  lib/
    validates_word_count.rb
    locale/
      en.yml

My YAML file looks like this:

en:
  validates_word_count:
    errors:
      messages:
        too_few_words: "has too few words (minimum is %d words)"
        too_many_words: "has too many words (maximum is %d words)"

However, if I call I18n.translate('validates_word_count.errors.messages.too_few_words'), I get this error:

translation missing: en, validates_word_count, errors, messages, too_few_words

How to configure my plugin / locale to work with I18n.translate ()?

+3
source share
1 answer

There are two parts to the answer.
1. Use a standard catalog layout:

validates_word_count/
init.rb
   lib/
     validates_word_count.rb
   config/
     locales/
       en.yml


2. In init.rb, add the following lines:

Dir[File.join("#{File.dirname(__FILE__)}/config/locales/*.yml")].each do |locale|
I18n.load_path.unshift(locale)
end
+3
source

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


All Articles