Take Off Labs | Ruby on Rails and iOS for web and mobile apps
x
63974806467 35963066f35b848753d8 512

Rails Internationalization with a Catch

over 5 years ago by Flavia
Tags: rails internationalization multiple applications customize translation multiple languages
Popup

In one of our projects, we had to create a series of applications which all behave in the same way, but have slightly different wording and branding (e.g., logo, landing page). To go about this, we could either create different applications and try to extract common code in gems or create one single application which somehow knows to use different assets depending on the server it is deployed to. We decided to go for the latter option and overload the mechanism responsible for Rails internationalization. Basically, we interpreted the multiple applications as being the same application translated in different languages. This allowed us to keep the code clean and maintainable across the application pool, develop adn test essential features much faster.

We started by creating a default locale file which stores all common expressions and acts as the fallback locale when an expression is not found in a specific language, e.g., en.yml.

en:
  about_page: "About Us"

We then added language files for each instance of the application, app1.yml, app2.yml etc.

app1:
  title: "My App 1"
app2:
  title: "My App 2"

In addition to the requirement above, each instance of the application allowed users to customize some of the texts shown, e.g., a label for a certain text field could be either Label Text 1 or Label Text 2. To support this, we also used the same I18n mechanism, but used a hierarchy of fallbacks. Each application instance has a number of additional language files which contain the specific strings. You can define the fallback hierarchy as follows – in application.rb:

config.i18n.fallbacks = {'app1_v1' => 'app1', 'app1' => 'en', 'app2_v1' => 'app2', 'app2' => 'en'}
config.i18n.default_locale = :app1

And that is pretty much it. With this, we were able to have one maintainable code base which serves multiple purposes. We deployed the same code base on different Heroku servers, each of them loading their corresponding language hierarchy. You can read more about Rails I18n API.

Did you like this post? Share it with your friends!