Le guide complet de l'internationalisation des rails (i18n)

Dans cet article, vous allez apprendre à traduire votre application Rails en plusieurs langues, à travailler avec des traductions, à localiser datetime et à changer de lieu. Nous allons voir tous ces aspects en action en créant un exemple d'application et en l'améliorant étape par étape. À la fin de l'article, vous aurez toutes les connaissances nécessaires pour commencer à mettre en œuvre ces concepts dans de vrais projets.

Préparer votre application Rails

Donc, comme je l'ai déjà dit, nous allons voir tous les concepts en action, donc créons une nouvelle application Rails en exécutant:

rails new SampleApp

Pour ce didacticiel, j'utilise Rails 5.2.1 , mais la plupart des concepts décrits s'appliquent également aux anciennes versions.

Maintenant, générons un StaticPagesControllerqui va avoir une indexaction (notre page principale):

rails g controller StaticPages index

Ajustez la views/static_pages/index.html.erbvue en ajoutant un exemple de contenu:

Welcome!

We provide some fancy services to good people.

J'aimerais également ajouter une page de commentaires où nos utilisateurs pourront partager leur opinion (espérons-le, positive) sur l'entreprise. Chaque commentaire aura le nom d'un auteur et le message réel:

rails g scaffold Feedback author message

Nous ne serons intéressés que par deux actions: new(qui va rendre le formulaire pour publier un avis et également lister tous les avis existants) et create(pour valider et persister effectivement les avis). Bien sûr, idéalement, les critiques devraient être pré-modérées, mais nous ne nous en occuperons pas aujourd'hui.

Ajustez l' newaction pour récupérer tous les avis de la base de données et les classer par date de création:

# feedbacks_controller.rb # ... def new @feedback = Feedback.new @feedbacks = Feedback.order created_at: :desc end

Je souhaite également rediriger l'utilisateur vers la page de commentaires lorsque le formulaire est traité et que le nouvel enregistrement est conservé:

# feedbacks_controller.rb # ... def create @feedback = Feedback.new(feedback_params) if @feedback.save redirect_to new_feedback_path else @feedbacks = Feedback.order created_at: :desc render :new end end

Rendez la collection de commentaires sur la newpage:

Enfin, créez un partiel pour un commentaire individuel:

Posted by

Prenez soin des itinéraires:

# config/routes.rb Rails.application.routes.draw do resources :feedbacks root 'static_pages#index' end

Enfin, ajoutez un menu global à la mise en page:

    Exécutez maintenant les migrations et démarrez le serveur:

    rails db:migrate rails s

    Accédez au //locahost:3000et assurez-vous que tout va bien. Maintenant que nous avons quelque chose sur quoi travailler, passons à la partie principale et localisons notre application.

    Un peu de configuration

    Avant d'effectuer des traductions, nous devons décider quelles langues seront prises en charge. Vous pouvez en choisir un, mais je m'en tiendrai au russe et à l'anglais, ce dernier étant défini par défaut. Reflétez ceci dans le config/application.rbfichier:

    # ... config.i18n.available_locales = [:en, :ru] config.i18n.default_locale = :en

    Connectez également un gem rails-i18n qui a des données locales pour différentes langues. Par exemple, il a traduit les noms des mois, les règles de pluralisation et d'autres éléments utiles.

    # Gemfile # ... gem 'rails-i18n'

    Installez simplement ce joyau et vous êtes prêt à partir:

    bundle install

    Stockage des traductions

    Maintenant que tout est configuré, prenons soin de la page d'accueil et traduisons le texte.

    Le moyen le plus simple de le faire est d'utiliser des vues localisées. Tout ce que vous avez à faire est de créer des vues nommées index.LANG_CODE.html.erb, où le LANG_CODEcorrespond à l'une des langues prises en charge. Donc, dans cette démo, nous devrions créer deux vues: index.en.html.erbet index.ru.html.erb. À l'intérieur, placez simplement le contenu pour la version anglaise et russe du site, et Rails choisira automatiquement la vue appropriée en fonction des paramètres régionaux actuellement définis. Pratique, hein?

    Cette approche n'est cependant pas toujours réalisable. Une autre façon serait de stocker vos chaînes traduites dans un fichier séparé et de rendre une version correcte de la chaîne en fonction de la langue choisie. Par défaut, Rails utilise des fichiers YAML qui doivent être stockés sous le config/localesrépertoire. Les traductions pour différentes langues sont stockées dans des fichiers séparés et chaque fichier porte le nom de cette langue.

    Ouvrez le config/localesdossier et notez qu'il y a déjà un en.ymlfichier à l'intérieur qui contient des exemples de données:

    en: hello: "Hello world"

    Donc, enest une clé de niveau supérieur représentant la langue à laquelle ces traductions sont destinées. Ensuite, il y a une paire clé-valeur imbriquée, où helloest la clé de traduction et Hello worldest la chaîne traduite réelle. Remplaçons cette paire par le contenu suivant:

    en: welcome: "Welcome!"

    Ceci est juste un message de bienvenue de notre page d'accueil. Créez maintenant un ru.ymlfichier dans le config/localesdossier et fournissez-y également un message d'accueil traduit:

    ru: welcome: "Добро пожаловать!"

    Nous venons de créer une traduction pour notre première chaîne, ce qui est vraiment génial.

    Effectuer des traductions simples

    Maintenant que nous avons rempli les fichiers YAML avec des données, voyons comment utiliser les chaînes traduites dans les vues. En fait, c'est aussi simple que d'utiliser la translateméthode qui est aliasée t. Cette méthode a un argument obligatoire: le nom de la clé de traduction:

    Lorsque la page est demandée, Rails recherche la chaîne qui correspond à la clé fournie et la restitue. Si la traduction demandée ne peut être trouvée, Rails rendra simplement la clé à l'écran (et la transformera en une forme plus lisible par l'homme).

    Translation keys can be named anything you like (well, nearly anything) but of course it is advised to give them some meaningful names so that you can understand what text they correspond to.

    Let’s take care of the second message:

    en: welcome: "Welcome!" services_html: "We provide some fancy services to good people."
    ru: welcome: "Добро пожаловать!" services_html: "Мы предоставляем различные услуги для хороших людей."

    Why do we need this _html postfix? Well, as you can see our string has some HTML markup, and by default Rails will render the em tag as plain text. As long as we don’t want this to happen, we mark the string as a “safe HTML”.

    Now just use the t method again:

    More On Translation Keys

    Our homepage is now localized, but let’s stop for a moment and think about what we have done. All in all, our translation keys have meaningful names, but what happens if we are going to have, say, 500 messages in the app? This number is actually not that big, and large websites may have thousands of translations.

    If all our key-values pairs are stored right under the en (or ru) key without any further grouping, this leads to two main problems:

    • We need to make sure that all the keys have unique names. This becomes increasingly complex as your application grows.
    • It is hard to locate all related translations (for example, translations for a single page or feature).

    Therefore, it would be a good idea to further group your translations under arbitrary keys. For example, you may do something like this:

    en: main_page: header: welcome: "Welcoming message goes here"

    The level of nesting is not limited (but you should be reasonable about it), and the keys in different groups may have identical names.

    It is beneficial, however, to follow the folder structure of your views (in a moment we will see why). Therefore, tweak the YAML files in the following way:

    en: static_pages: index: welcome: "Welcome!" services_html: "We provide some fancy services to good people."
    ru: static_pages: index: welcome: "Добро пожаловать!" services_html: "Мы предоставляем различные услуги для хороших людей."

    Generally, you need to provide full path to the translation key when referencing it in the t method:

    However, there is also a “lazy” lookup available. If you perform translation in a view or controller, and the translation keys are namespaced properly following the folder structure, you may omit the namespaces all together. This way, the above code turns to:

    Note that the leading dot is required here.

    Let’s also translate our global menu and namespace the translations properly:

    en: global: menu: home: "Home" feedback: "Feedback"
    ru: global: menu: home: "Главная" feedback: "Отзывы"

    In this case we can’t take advantage of the lazy lookup, so provide the full path:

      Translating Models

      Now let’s proceed to the Feedback page and take care of the form. The first thing we need to translate is the labels for the inputs. It appears that Rails allows us to provide translations for the model attributes, and they will be automatically utilized as needed. All you need to do is namespace these translations properly:

      en: activerecord: attributes: feedback: author: "Your name" message: "Message"
      ru: activerecord: attributes: feedback: author: "Ваше имя" message: "Сообщение"

      The labels will now be translated automatically. As for the “submit” button, you can provide translation for model itself by saying:

      en: activerecord: models: feedback: "Feedback"

      But honestly I don’t like the “Create Feedback” text on this button, so let’s stick with a generic “Submit” word:

      en: global: forms: submit: Submit
      ru: global: forms: submit: Отправить

      Now utilize this translation:

      Error Messages

      Probably we do not want the visitors to post empty feedback messages, therefore provide some simple validation rules:

      # models/feedback.rb # ... validates :author, presence: true validates :message, presence: true, length: {minimum: 5}

      But what about the corresponding error messages? How do we translate them? It appears that we don’t need to do anything at all as rails-i18n gem already knows how to localize common errors. For example, this file contains error messages for the Russian locale. If you actually do want to tweak the default error messages, then check the official doc that explains how to achieve that.

      One problem with the form, however, is that the error messages subtitle (the one that says “N errors prohibited this feedback from being saved:”) is not translated. Let’s fix it now and also talk about pluralization.

      Pluralization Rules

      As long as potentially there can be one or more error messages, the “error” word in the subtitle should be pluralized accordingly. In English words are usually pluralized by adding an “s” postfix, but for Russian the rules are a bit more complex.

      I already mentioned that the rails-i18n gem contains pluralization rules for all the supported languages, so we don’t need to bother writing them from scratch. All you need to do is provide the proper key for each possible case. So, for English there are only two possible cases: one error or many errors (of course, there can be no errors, but in this case the message won’t be displayed at all).

      en: global: forms: submit: Submit messages: errors: one: "One error prohibited this feedback from being saved" other: "%{count} errors prohibited this feedback from being saved"

      The %{count} here is interpolation – we take the passed value and place it right into the string.

      Now take care of the Russian locale which has more possible cases:

      ru: global: forms: submit: Отправить messages: errors: one: "Не удалось сохранить отзыв! Найдена одна ошибка:" few: "Не удалось сохранить отзыв! Найдены %{count} ошибки:" many: "Не удалось сохранить отзыв! Найдено %{count} ошибок:" other: "Не удалось сохранить отзыв! Найдена %{count} ошибка:"

      Having this in place, just utilize these translation:

      Note that in this case we pass the translation key as well as the value for the count variable. Rails will take the proper translation variant based on this number. Also the value of the count will be interpolated into each %{count} placeholder.

      Our next stop is the _feedback.html.erb partial. Here we need to localize two strings: “Posted by…” and datetime (created_at field). As for “Posted by…”, let’s just utilize the interpolation again:

      en: global: feedback: posted_by: "Posted by %{author}"
      ru: global: feedback: posted_by: "Автор: %{author}"

      But what about the created_at? To take care of it, we can take advantage of the localize method aliased as just l. It is very similar to the Ruby’s strftime, but produces a translated version of the date (specifically, the months’ names are translated properly). Let’s use a predefined format called :long:

      If you would like to add your very own format, it is possible too as explained here.

      Switching Between Locales

      So, our app is now fully translated… but there is a very minor thing: we cannot change the locale! Come to think of it, this is quite a major issue really, so let’s fix it now.

      There are a handful of possible ways of setting and persisting the chosen locale across the requests. We are going to stick with the following approach:

      • Our URLs will have an optional :locale parameter, and so they’ll look like //localhost:3000/en/some_page
      • If this parameter is set and the specified locale is supported, we translate the app into the corresponding language
      • If this parameter is not set or the locale is not supported, set a default locale

      Sounds straightforward? Then let’s dive into the code!

      First of all, tweak the routes.rb by including a scope:

      # config/routes.rb scope "(:locale)", locale: /#")/ do # your routes here... end

      Here we are validating the specified parameter using a RegEx to make sure that the locale is supported (note that the anchor characters like \A are not permitted here).

      Next, set a before_action in the ApplicationController to check and set the locale on each request:

      # application_controller.rb # ... before_action :set_locale private def set_locale I18n.locale = extract_locale || I18n.default_locale end def extract_locale parsed_locale = params[:locale] I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil end

      Also, in order to persist the chosen locale across the requests, set the default_url_options:

      # application_controller.rb # ... private def default_url_options { locale: I18n.locale } end

      The is going to include the locale parameter into every link generated with Rails helpers.

      The last step is to present two links to switch between locales:

          As an exercise, you may make these links more fancy and, for instance, redirect the user back to the page that he was browsing.

          Simplify Your Life With Lokalise

          By now you are probably thinking that supporting multiple languages on a big website is probably a pain. And, honestly, you are right. Of course, the translations can be namespaced, and even split into multiple YAML files if needed, but still you must make sure that all the keys are translated for each and every locale.

          Luckily, there is a solution to this problem: the Lokalise platform that makes working with the localization files much simpler. Let me guide you through the initial setup which is nothing complex really.

          • To get started, grab your free trial
          • Install Lokalise CLI that will be used to upload and download translation files
          • Open your personal profile page, navigate to the “API tokens” section, and generate a read/write token
          • Create a new project, give it some name, and set English as a base language
          • On the project page click the “More” button and choose “Settings”. On this page you should see the project ID
          • Now from the command line simply run lokalise --token import --lang_iso en --file config/locales/en.yml while providing your generated token and project ID (on Windows you may also need to provide the full path to the file). This should upload English translation to Lokalise. Run the same command for the Russian locale.
          • Navigate back to the project overview page. You should see all your translation keys and values there. Of course, it is possible to edit, delete them, as well as add new ones. Here you may also filter the keys and, for example, find the untraslated ones which is really convenient.
          • After you are done editing the translations, download them back by running lokalise --token export --type yaml --bundle_structure %LANG_ISO%.yml --unzip_to E:/Supreme/docs/work/lokalise/rails/SampleApp/config/locales/. Great!

          Lokalise has many more features including support for dozens of platforms and formats, ability to order translations from professionals, and even the possibility to upload screenshots in order to read texts from them. So, stick with Lokalise and make your life easier!

          Conclusion

          In this article we have thoroughly discussed how to introduce internationalization support in Rails applications and implemented it ourselves. You have learned how and where to store translations, how to look them up, what are localized views, how to translate error messages and ActiveRecord-related stuff, as well as how to switch between locales and persist the chosen locale among the request. Not bad for today, eh?

          Of course, it is impossible to cover all ins and outs of Rails I18n in one article, and so I recommend checking out the official guide that gives some more detailed information on the topic and provides useful examples.

          Originally published at blog.lokalise.co on August 23, 2018.