Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to avoid I18n::InvalidLocale?

I get a I18n::InvalidLocale: "zh-CN" is not a valid locale exception that I want to avoid.

To solve it, I have heard of two hacks:

# meh
config.i18n.enforce_available_locales = false

# Ever heard of convention over configuration?
config.i18n.available_locales = [:fr, :en, "zh-CN", "zh-TW"]

None of them seem clean to me, because without touching those configuration variables, I already have a bunch of available locales which are automagically pre-filled:

My current available_locales are:

> I18n.available_locales
=> [:en, :fr]   (misses zh-CN and zh-TW)

In my config/locales folder, I have:

en.yml
fr.yml
zh-CH.yml (newly added, and unavailable)
zh-TW.yml (newly added, and unavailable)

In my config/application.rb, I have:

config.i18n.default_locale = :fr

I don't get how fr has automagically entered I18n.available_locales, when the zh-CN and zh-TW have not.

Yet, having fr enter it without me setting config.i18n.available_locales tells me that touching this configuration variable is not the clean way to go.

Do you have a hint at avoiding the I18n::InvalidLocale exception at the correct level?

like image 465
Gwendal Roué Avatar asked Sep 25 '15 08:09

Gwendal Roué


1 Answers

The i18n library takes a pragmatic approach to locale keys , including only the locale ("language") part, like :en, :pl, not the region part, like :en-US or :en-GB, if you want this type of defination check Few gems such as Globalize3 it may help you.

Also check this descussion also go through with this

And Also remove the config.i18n.default_locale = :fr Because with default locals it will through the same error which you mentioned so after removing defaullt use this config.i18n.available_locales = [:fr, :en, "zh-CN", "zh-TW"]

like image 72
Arvind Avatar answered Sep 21 '22 13:09

Arvind