Rööbaste rahvusvahelistumise täielik juhend (i18n)

Selles artiklis saate õppida, kuidas oma Rails-rakendust mitmesse keelde tõlkida, töötada tõlgetega, lokaliseerida kuupäeva ja vahetada lokaale. Näeme kõiki neid aspekte tegevuses, luues näidisrakenduse ja seda samm-sammult täiustades. Artikli lõpuks on teil olemas kõik vajalikud teadmised nende kontseptsioonide rakendamiseks reaalsetes projektides.

Rakenduse Rails ettevalmistamine

Niisiis, nagu ma juba ütlesin, näeme kõiki mõisteid toimimas, seetõttu loome käivitades uue rakenduse Rails:

rails new SampleApp

Selle õpetuse jaoks kasutan Rails 5.2.1 , kuid enamik kirjeldatud mõisteid kehtib ka vanemate versioonide kohta.

Nüüd genereerime a, StaticPagesControllermillel on indextoiming (meie peamine leht):

rails g controller StaticPages index

Muutke views/static_pages/index.html.erbvaadet, lisades näidissisu :

Welcome!

We provide some fancy services to good people.

Samuti tahaksin lisada tagasiside lehe, kus meie kasutajad saavad ettevõtte kohta oma arvamust (loodetavasti positiivset) jagada. Igal tagasisidel on autori nimi ja tegelik sõnum:

rails g scaffold Feedback author message

Meid huvitavad ainult kaks toimingut: new(mis muudab vormi arvustuse postitamiseks ja loetleb ka kõik olemasolevad ülevaated) ja create( arvustuste tegelikult kinnitamiseks ja jätkamiseks). Muidugi peaks ideaaljuhul olema ülevaated eelnevalt modereeritud, kuid me ei vaevu seda täna.

Muutke newtoimingut kõigi arvustuste andmebaasist toomiseks ja järjestamiseks loomise kuupäeva järgi:

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

Samuti sooviksin kasutaja suunata tagasiside lehele, kui vorm on töödeldud ja uus kirje püsib:

# 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

Esitage tagasisidetekogu newlehel:

Lõpuks looge individuaalse tagasiside jaoks osaline:

Posted by

Hoolitse marsruutide eest:

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

Lõpuks lisage paigutusele üldmenüü:


    

    Nüüd käivitage migreerimised ja käivitage server:

    rails db:migrate rails s

    Navigeerige lehele //locahost:3000ja veenduge, et kõik oleks korras. Nüüd, kui meil on midagi tööd teha, jätkame põhiosaga ja lokaliseerime oma rakenduse.

    Natuke konfiguratsiooni

    Enne tõlkimist peame otsustama, milliseid keeli toetatakse. Võite valida ükskõik millise, kuid jään vene ja inglise keele juurde, vaikimisi on viimane seatud. Peegeldage seda config/application.rbfaili sees :

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

    Ühendage ka rails-i18n pärl, millel on erinevate keelte lokaadiandmed. Näiteks on see tõlkinud kuude nimetusi, pluraliseerimisreegleid ja muud kasulikku.

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

    Lihtsalt installige see pärl ja teil on hea minna:

    bundle install

    Tõlgete salvestamine

    Nüüd, kui kõik on konfigureeritud, hoolitseme avalehe eest ja tõlgime seal teksti.

    Lihtsaim viis selleks on lokaliseeritud vaadete kasutamine. Kõik, mida peate tegema, on luua nimega vaated index.LANG_CODE.html.erb, kus see LANG_CODEvastab ühele toetatud keeltest. Nii et selles demos peaksime looma kaks vaadet: index.en.html.erbja index.ru.html.erb. Sisestage lihtsalt saidi inglis- ja venekeelse versiooni sisu ning Rails valib praegu määratud lokaadi põhjal automaatselt õige vaate. Mugav, jah?

    Selline lähenemine pole aga alati teostatav. Teine võimalus oleks hoida oma tõlgitud stringid eraldi failis ja renderdada valitud keele põhjal stringist õige versioon. Vaikimisi kasutab Rails YAML-faile, mis tuleb config/localeskataloogi salvestada . Erinevate keelte tõlked salvestatakse eraldi failidesse ja iga fail on nimetatud selle keele järgi.

    Avage config/localeskaust ja pange tähele, et seal on juba en.ymlfail, millel on mõned näidisandmed:

    en: hello: "Hello world"

    Niisiis, enon tipptasemel võti, mis tähistab keelt, mille jaoks need tõlked on mõeldud. Järgmisena on pesastatud võtme-väärtuste paar, kus helloon tõlkevõti ja Hello worldtegelik tõlgitud string. Asendame selle paari järgmise sisuga:

    en: welcome: "Welcome!"

    See on lihtsalt tervitatav sõnum meie kodulehelt. Nüüd looge kausta ru.ymlfail config/localesja edastage seal ka tõlgitud tervitussõnum:

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

    Oleme just loonud tõlke oma esimesele stringile, mis on tõesti suurepärane.

    Lihtsate tõlgete sooritamine

    Nüüd, kui oleme YAML-failid asustatud mõningate andmetega, vaatame, kuidas tõlgitud stringe vaates kasutada. Tegelikult on see sama lihtne kui kasutada translatevarjatud meetodit t. Sellel meetodil on üks nõutav argument: tõlkevõtme nimi:

    Kui leht on taotletud, otsib Rails üles antud võtmele vastava stringi ja renderdab selle. Kui taotletud tõlget ei õnnestu leida, renderdab Rails võtme lihtsalt ekraanil (ja muudab selle inimesele paremini loetavaks vormiks).

    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

          Selles artiklis oleme põhjalikult arutanud, kuidas juurutada Railsi rakendustes rahvusvahelistumise tuge ja seda ka ise rakendada. Olete õppinud, kuidas ja kuhu tõlkeid salvestada, kuidas neid otsida, millised on lokaliseeritud vaated, kuidas tõlkida veateateid ja ActiveRecordiga seotud asju, samuti kuidas vahetada lokaatide vahel ja säilitada valitud lokaat päringu hulgas. Pole tänaseks halb, eks?

          Muidugi on võimatu hõlmata kõiki Rails I18n häid külgi ühes artiklis ja seetõttu soovitan tutvuda ametliku juhendiga, mis annab selle teema kohta üksikasjalikumat teavet ja pakub kasulikke näiteid.

          Algselt avaldatud aadressil blog.lokalise.co 23. augustil 2018.