by Stéphane A., on 02 May 2012
First and foremost, internationalizing an existing application is a tedious, repetitive task. So even though your customer may not need it as part of the first development, paying attention to this aspect is not only recommended, but often turns out to be quite necessary. This will avoid a lot of trouble for you in the long run!
Here are some techniques, tools and tips that will help you get started. But first, let’s review how i18n (I’m not typing that word a second time) works in Rails.
First of all, you don’t need any extra gem to internationalize your application. Everything is already built into the framework.
The default language is English (
:en), and all your translations (in YAML files) are stored into
The format of these files is relatively free, except for the names of ActiveRecord models and attributes, and validation error messages. As usual with Rails, conventions exist and the process will be a lot easier if you follow them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
You can put all your texts in a single file (such as
en.yml), but we recommend splitting them into different theme files, which must be name
The first thing you need to do is set the locale of the application. Here is how you would do it if your
User model has a stored locale:
1 2 3 4 5 6 7
Now that we know which local to use, we need to replace all the text in our views, controllers, etc by a method code, which will select the correct translation. This is the
translate(key) method (aliased to
t for short). This method is automatically available in views. In controllers, you will need to call
As said before, the translation files have conventions as to their structure. Here is where they will prove useful: let’s say you want to display the text “Print this page” (line 48), you could call
t('orders.footer.print_page'), but that is a little long, especially if you consider you will have to do this for every single link, button, header and paragraph of your view (I warned you it was tedious). But if you’re in
app/views/orders/_footer.html.erb, you can simply call
t('.print_page'). Rails will know to complete the missing hierarchy of your key with the path to the current view or partial. Of course, you can still use the complete path whenever you need to access translations outside your current scope.
Read more: I18n on RailsGuides