Tag Archives: i18n

Mongoid localize

If you’re using Mongoid and you need to translate the content of a field in multiple languages (locales) here’re the steps how to do it without additional gems by using “localize” attribute for a field. For example, here’s a simple “Page” model (rails):

class Page
  include Mongoid::Document

  field :title, type: String, localize: true, default: ""
  field :text, type: String, localize: true, default: ""
end

As you can see, we’ve added “localize: true” to our field definition, which means that our field will be stored with this structure:

{
  ...
  "title" : { "en" : "About us", "it" : "Chi siamo" },
  "text" : { "en" : "English lorem ipsum...", "it" : "Italian lorem ipsum..." }
  ...
}

I’ve set also the default value to an empty string because for some reason when you init a new record it’s initialized with {} ( for ex: {“en” : “{}”} ) instead as a empty string or a null value.Then in your views just print as it was a normal field, for example:

page.title

To display the field in a different language just change the locale with I18n.locale = “xx”.
The same way works also update_attributes, just pass it from the form as it was an normal field and call page.update_attributes(params[:page]) for example.

sinatra and i18n gem

To make work i18n gem and sinatra in your config.ru add:

# include the gem, otherwise add it to your bundle file if you manage gems with bundler.
require 'i18n'

# assuming that you have your locale files (.yml) in ./config/locales directory
I18n.load_path += Dir[File.join(File.dirname(__FILE__), 'config', 'locales', '*.yml').to_s]

Then somewhere in you app add the t() helper:

helpers do
  def t(*args)
    I18n.t(*args)
  end
end

Happy internationalizing!