Translate dynamic content using Globalize gem
Img source: railscasts.com
We are in an interconnected world, where people across the planet can use the projects that we develop, and having the opportunity to offer them with additional international languages make them a lot better. We can obviously use locale for doing the translations of static strings like labels, or placeholder descriptions that appear across our applications, so we should also have something that can give us a way to translate the dynamic content. There is a really great Ruby gem that makes the translation of model attributes a lot easier. This gem is called Globalize and is very easy to use.
You can install it quick and easy, as any other Ruby gem.
After you have installed it, you can start to use it.
Whether you are trying to create a new model and then translate that model’s attributes, or trying to translate the data from an existing model, you will need to create a new migration for creating a new table. Then, this table will be used as a utility that is tied to the table of the model that we are intending to do the translations for. For example, we may have a model called Post, and then want to translate the title and the name of this posts from this model. To do that, we must generate a migration similar to the following:
TranslatePosts < ActiveRecord::Migration
def self.up
Post.create_translation_table!({
:title => :string,
:text => :text
}, {
:migrate_data => true,
:remove_source_columns => true
})
end
def self.down
Post.drop_translation_table! :migrate_data => true
end
end
Then we also need to add the following at the Post model:
translates :title, :text
After we are done with this, we can now see that we have already new associations added to posts instances.
class Post < ActiveRecord::Base
translates :title, :name
end
puts post.translations.inspect
# => [#<Post::Translation id: 1, post_id: 1, locale: "en", title: "Globalize rocks!", name: "Globalize">,
#<Post::Translation id: 2, post_id: 1, locale: "nl", title: '', name: nil>]
I18n.locale = :en
post.title # => 'Globalize rocks!'
post.name # => 'Globalize'
I18n.locale = :nl
post.title # => ''
post.name # => 'Globalize'
You can also watch an example of this gem being used in a Rails application by watching the brief episode from RailsCast:
https://www.youtube.com/watch?v=guVFKjAd2ec
You can go to this gem’s GitHub page to view its source code, and learn more about.