Den komplette vejledning til internationalisering af skinner (i18n)

I denne artikel vil du lære at oversætte din Rails-applikation til flere sprog, arbejde med oversættelser, lokalisere datetid og skifte lokalitet. Vi vil se alle disse aspekter i aktion ved at oprette en prøveapplikation og forbedre den trin for trin. Ved slutningen af ​​artiklen har du al den nødvendige viden til at begynde at implementere disse koncepter i rigtige projekter.

Forberedelse af din Rails-app

Så som jeg allerede sagde, vil vi se alle koncepter i aktion, lad os derfor oprette en ny Rails-applikation ved at køre:

rails new SampleApp

Til denne tutorial bruger jeg Rails 5.2.1 , men de fleste af de beskrevne koncepter gælder også for ældre versioner.

Lad os nu generere en, StaticPagesControllerder vil have en indexhandling (vores hovedside):

rails g controller StaticPages index

Tilpas views/static_pages/index.html.erbvisningen ved at tilføje noget prøveindhold:

Welcome!

We provide some fancy services to good people.

Jeg vil også gerne tilføje en feedback-side, hvor vores brugere vil være i stand til at dele deres mening (forhåbentlig en positiv) om virksomheden. Hver feedback vil have forfatterens navn og den aktuelle besked:

rails g scaffold Feedback author message

Vi vil kun være interesseret i to handlinger: new(som vil gengive formularen til at indsende en anmeldelse og også liste alle eksisterende anmeldelser) og create(for faktisk at validere og fortsætte anmeldelserne). Naturligvis skal anmeldelser ideelt set præ-modereres, men vi gider ikke med dette i dag.

Tilpas newhandlingen for at hente alle anmeldelser fra databasen og bestille dem efter oprettelsesdato:

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

Jeg vil også gerne omdirigere brugeren til siden Feedback, når formularen behandles, og den nye post er vedvarende:

# 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

Geng feedback-samlingen på newsiden:

Til sidst skal du oprette en del til en individuel feedback:

Posted by

Pas på ruterne:

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

Til sidst tilføj en global menu til layoutet:


    

    Kør nu migreringer og start serveren op:

    rails db:migrate rails s

    Naviger til //locahost:3000og sørg for, at alt er i orden. Nu hvor vi har noget at arbejde med, lad os gå videre til hoveddelen og lokalisere vores ansøgning.

    En smule konfiguration

    Før vi udfører oversættelser, skal vi beslutte, hvilke sprog der understøttes. Du kan vælge en hvilken som helst, men jeg vil holde mig til russisk og engelsk, hvor sidstnævnte er angivet som standard. Reflekter dette i config/application.rbfilen:

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

    Tilslut også en skinne-i18n-perle, der har lokal data for forskellige sprog. For eksempel har det oversat månedsnavne, pluraliseringsregler og andre nyttige ting.

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

    Installer bare denne perle, så er du klar:

    bundle install

    Lagring af oversættelser

    Nu hvor alt er konfigureret, lad os tage os af hjemmesiden og oversætte teksten der.

    Den enkleste måde at gøre dette på er ved at bruge lokaliserede visninger. Alt hvad du skal gøre er at oprette visninger med navnet index.LANG_CODE.html.erb, hvor det LANG_CODEsvarer til et af de understøttede sprog. Så i denne demo skulle vi oprette to visninger: index.en.html.erbog index.ru.html.erb. Inde skal du bare placere indhold til engelsk og russisk version af webstedet, og Rails vælger automatisk den korrekte visning baseret på det aktuelt indstillede landestandard. Praktisk, ikke?

    Denne tilgang er imidlertid ikke altid mulig. En anden måde ville være at gemme dine oversatte strenge i en separat fil og gengive en korrekt version af strengen baseret på det valgte sprog. Som standard anvender Rails YAML-filer, der skal gemmes under config/localesbiblioteket. Oversættelser til forskellige sprog gemmes i separate filer, og hver fil er opkaldt efter dette sprog.

    Åbn config/localesmappen og bemærk, at der allerede er en en.ymlfil inde med nogle eksempler på data:

    en: hello: "Hello world"

    ener en topnøgle, der repræsenterer det sprog, som disse oversættelser er beregnet til. Dernæst er der et indlejret nøgleværdipar, hvor helloer oversættelsesnøglen og Hello worlder den faktiske oversatte streng. Lad os erstatte dette par med følgende indhold:

    en: welcome: "Welcome!"

    Dette er bare en indbydende besked fra vores hjemmeside. Opret nu en ru.ymlfil i config/localesmappen og lever også en oversat indbydende besked:

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

    Vi har lige oprettet oversættelse til vores første streng, hvilket er rigtig godt.

    Udførelse af enkle oversættelser

    Nu hvor vi har udfyldt YAML-filerne med nogle data, lad os se, hvordan vi bruger de oversatte strenge i visningerne. Faktisk er det så simpelt som at bruge den translatemetode, der er alias som t. Denne metode har et krævet argument: navnet på oversættelsesnøglen:

    Når siden anmodes om, ser Rails den streng, der svarer til den angivne nøgle, op og gengiver den. Hvis den anmodede oversættelse ikke kan findes, gengiver Rails bare nøglen på skærmen (og vender den til en mere menneskelig læsbar form).

    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

          I denne artikel har vi grundigt diskuteret, hvordan man introducerer internationaliseringsstøtte i Rails-applikationer og implementerer den selv. Du har lært, hvordan og hvor man kan gemme oversættelser, hvordan man ser dem op, hvad der er lokaliserede visninger, hvordan man oversætter fejlmeddelelser og ActiveRecord-relaterede ting, samt hvordan man skifter mellem lokaliteter og fastholder det valgte sted blandt anmodningen. Ikke dårligt for i dag, ikke?

          Det er selvfølgelig umuligt at dække alle detaljer i Rails I18n i en artikel, og derfor anbefaler jeg at tjekke den officielle guide, der giver nogle mere detaljerede oplysninger om emnet og giver nyttige eksempler.

          Oprindeligt offentliggjort på blog.lokalise.co den 23. august 2018.