Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add available locales to i18n for a Ruby only project?

I'm working on a Ruby only project (not Ruby on Rails) that uses Mongoid for persistence. Mongoid supports language translations using I18n via localized fields: http://mongoid.org/en/mongoid/docs/documents.html#localized_fields

However, I can't figure out how to add additional locales as a configuration option. I18n.available_locales reports only :en

All the searching I've done shows how to configure and use I18n within the context of Rails. Can anyone help me with how to configure I18n and add additional locales so that I can set localized field values for the Mongoid documents.

Thanks!

like image 354
Dan Sharp Avatar asked Feb 25 '15 13:02

Dan Sharp


People also ask

How to manage locales across requests in rails i18n?

In addition to Rails i18n, we have not yet discussed the different ways to manage locales across requests. By default, Rails is going to use locale set in the I18n.default_locale (which is :en or any other value you define in the configuration) or the value from I18n.locale if it was explicitly defined.

What is i18n Ruby on rails?

The Ruby I18n (shorthand for internationalization) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or for providing multi-language support in your application.

How do I set the locale of the application in Ruby?

A very common place to set locale is the before_action inside the ApplicationController: application_controller.rb [...] before_action :set_locale private def set_locale I18n.locale = extract_locale || I18n.default_locale end [...]

How does the i18n library handle locale keys?

The i18n library takes a pragmatic approach to locale keys (after some discussion), including only the locale ("language") part, like :en, :pl, not the region part, like :en-US or :en-GB, which are traditionally used for separating "languages" and "regional setting" or "dialects".


2 Answers

Wow.

I don't know how I overlooked it, but it was simpler than I thought:

I18n.available_locales = [:fr, :de, :es, :en]

I can drop that in an initializer and be good to go.

like image 96
Dan Sharp Avatar answered Oct 22 '22 00:10

Dan Sharp


Also if you want to list that includes symbolized and string versions which can be handy if you have to check both types.

> I18n.config.available_locales_set
=> [
    [ 0] "en",
    [ 1] :en,
    [ 2] "en-GB",
    ...
like image 37
newdark-it Avatar answered Oct 22 '22 02:10

newdark-it