Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Danh sách Kiểm tra Hoàn chỉnh cho Quốc tế hóa Devise trong Rails App

Đôi khi, best blog post đến từ nhu cầu scratch your own itch. Bài blog hôm nay là ví dụ!

Bạn chắc biết Devise — popular authentication solution cho Rails applications. Khi làm việc với Devise, tôi thấy get translation up and running phức tạp hơn anticipated. Past me wish có checklist guide tôi through process.

Vậy đây nó — cho future me và bạn — ultimate Devise Internationalization Checklist!

Khi Nào (Không) Dùng Gem devise-i18n?

Policy của Devise là không make strings trong Devise views translatable. All strings hard coded. Kudos cho creators của devise-i18n gem, làm cho all Devise templates translatable và cung cấp community-sourced translations. Cho international apps cần multi-language support, devise-i18n gem là easiest solution.

Tuy nhiên, devise-i18n gem explicitly chọn follow Devise text as closely as possible. Nhưng text Devise cung cấp không consistent. Và literal translation never generate fluent language, tôi constantly tweak translations (và copy files giữa projects). Ongoing struggle vì hard get all translations consistent khi nhìn one string hoặc one view tại một thời điểm.

Kết quả, translation quality của i18n-devise gem không đạt standards cho projects monolingual, Dutch-only của tôi.

Disadvantage khác của gem arise với customized views. Dù chỉ styling, mọi update của devise-i18n gem touch changes Devise made to views, sẽ mean bạn phải fix things. Bạn sẽ either regenerate views và apply customizations hoặc copy/paste changes vào views. Problem này không solved với approach trong checklist below, nhưng cũng không difficult hơn without devise-i18n gem. 🤷‍♀

🇳🇱 A Dutch treat

Tôi quyết định tạo một Dutch translation file đẹp cho Devise, và không bao giờ lo về nó nữa. Nghe như treat? Bạn tìm thấy new and improved translation file trên GitHub. Xem step 3 trong checklist. Rationale cho mỗi translation decision explained in file.

The Ultimate Checklist

Bay solo với :nl translation, bắt đầu với all details và check boxes.

Lưu ý: assume bạn có app ready, với Devise added và installed với User model, và Devise views generated. Nếu code along: đây là starting point. Và note nl trong *.nl.yml có thể replace bằng language bạn chọn, User và :user replace bằng model name bạn dùng trong Devise.

Step One: Set locale

Thêm :nl vào available locales (nếu không strong opinion, start với put nó trong application.rb for now). Giờ set as default.

# application.rb
config.i18n.available_locales = [:nl, :en]
config.i18n.default_locale = :nl

Có better, cleaner options set locale hơn thêm vào application.rb. Check Rails i18n guide sau đọc post để choose option suit you best.

Step Two: Add Rails translation

Thêm Rails :nl translation file take care of strings in interface không Devise specific (đặc biệt Rails validation error messages).

Step Three: The Devise keys

Translate Devise keys to :nl: add the New and Improved Dutch Translation! (Link above 🇳🇱)

Step Four: Create views.*.yml files

Thêm Dutch và English .yml files cho views, views.*.yml. Có example finished views.nl.yml file trong repo, reflecting steps 4, 6 and 7.

#example views.nl.yml
nl:
  devise:
    # to be filled in later with Devise scopes:
    # registrations:
    #   new:
    #     forget_password: Wachtwoord vergeten?

Step Five: The Active Record attributes

Giờ, add translations cho labels của Active Record attributes, như email và password. Translate just ones user và admin user thấy, cho each module bạn implemented. Không cần translate token names (như i18n gem làm). Đây là những gì tôi consider useful 'translatables':

# In: active_record.nl.yml
# translating the labels that map to User attributes
nl:
  activerecord:
    attributes:
      user:
        current_password: Huidig wachtwoord
        email: e-mailadres
        password: wachtwoord
        password_confirmation: Wachtwoord bevestigen
        remember_me: Ingelogd blijven?
    models:
      user: Gebruiker

Lưu ý :email và :password values downcased. Đó là vì tweaks Rails error messages step 7.

For now, put keys in active_record.*.yml.

Step Six: Check every Devise view

Tiếp, all Devise-specific templates và strings cần i18n-ed với corresponding translations. Làm yourself annoying job. Trước khi dive, xem shortcuts nào work for you:

  • Could use 118n-devise gem cho views, nhưng vẫn phải copy keys từ gem's .yml files vào project's .yml files. Gem interleaves chúng trong devise.*.yml, nhưng chúng ta không muốn overwrite nice new Dutch translation. Và nếu bạn styled Devise views, cần copy styling too. Yugh.
  • Nếu đã có i18n-ed projects, could copy view files. (Same disadvantages previous option.)
  • Use repo cho examples vài views tôi used in latest project.

Hoặc solve once and for all: head down, create set files bạn dùng from now on, exactly the way you want them to be. Examples previous step là first version của tôi; chúng có thể help kick-start your own. Check out mini-checklist below cho all requirements.

Mini Checklist for the Devise Forms

  • Strings không phải Active Record strings cần i18n-ed và có (properly scoped) keys và translations (stored in, ví dụ, views.*.yml file — xem example).
  • Take care Dutch translations, khi adding own, consistent với new devise.nl.yml.
  • Ignore downcased labels; chúng sẽ capitalized properly step 7.
  • Nếu đã có mailers i18n-ed, okay. Nếu không, may ignore until step 8.
  • Các Devise views sau cần make translatable với Rails translate (t) helper:
    • Partial devise/views/shared/_links: all link names;
    • Partial devise/views/shared/_errors (since Devise 4.6)
    • Trong Devise forms cho each module bạn dùng: all strings không phải labels cho Active Record attributes.

Step Seven: The Active Record error messages

Tiếp, tweak Active Record error messages related to Devise functionality. Như "password can't be blank", và other validations.

Vấn đề: now upgraded Devise translations, Active Record messages cần tweak cũng vì inconsistency in style really showing. Tôi tweak chúng too, following same rules as Devise translations, making sure consistent.

Bạn thấy format messages changed: từ "%{attribute} %{message}" sang "%{message}". Giờ reference attribute within translated string thay vì force nó at start of string, makes it so much easier prettify Dutch messages. Tôi rather have duplication than putting up with sometimes weird messages.

New message format là lý do step 5 email và password attributes cần downcased: trong error messages, chúng có thể appear anywhere within a sentence.

Tôi cũng replace :taken message. Devise policy là không reveal nếu email 'not found' hoặc 'invalid'. Tôi extend policy đó đến Rails' taken message.

Xem file này nếu muốn follow new messages style. Sau đó replace corresponding part của Rails error: messages: keys trong original nl.yml file. One caveat: khi adding validations cho none Devise-related input, please double check nếu error messages still make sense. (Tôi need investigate further; chỉ checked ones related to Devise.)

Step Eight: Fix the labels we just broke

Step 5, downcased email và password translations cho use trong new error messages. Giờ cần fix appearance của chúng trong labels. Có several options, nhưng one I like most: adding separate 'label' keys.

Điều này add some duplication cho user keys, nhưng keep labels in forms clean.

# in active_record.nl.yml add the label helper keys:
nl:
  activerecord:
    attributes:
      user:
        current_password: Huidig wachtwoord
        email: e-mailadres
        password: wachtwoord
        password_confirmation: Herhaal het wachtwoord
        remember_me: Wil je ingelogd blijven?
    models:
      user: Gebruiker
    helpers:
      label:
        user:
          email: Emailadres
          password: Wachtwoord

Lưu ý đã có :helpers scope trong original nl.yml. In general, good idea keep keys cho scope together, easy lookup (by humans).

Other changes straightforward. No big surprises từ đây. 🎉.

Step Nine: Update navigation links

Tìm all links point to Devise (think navigation) và i18n them với Rails t helper.

Tôi like keep those somewhere in Devise scope của .yml's. Ví dụ, add t("devise.sign_out") để có :sign_out trong same scope as :sign_up và :sign_in (xem example files).

Step Ten: Translate the mailers.

Translate mailer views. Có few options:

  • Bạn có thể 'i18n' every string và link name, just like step 6 với other views. May want add separate mailer.*.yml.
  • Hoặc add separate mailer views cho each locale: devise/mailer/reset_password.nl.html.erb và devise/mailer/reset_password.en.html.erb. Mỗi cái với own text. Rails pick one match locale set.

Xong! Giờ all Devise strings properly translated. Yay!

After Care: Declutter

Trong views example, tôi extracted shared keys (như :forgot_password) và collected chúng trong general devise scope. Makes easier change them, nhưng Rails không auto find, cần verbose syntax (t("devise.forgot_password")), vì dot syntax (t(".new_confirmation_mail")) won't work.

Nếu go with active_record.*.yml, makes sense collect all keys với active record scope vào file đó. Move Active Record keys từ Rails *.yml files vào corresponding active_record.*.yml.

Cũng có two pairs *.yml files duplicate devise: scope. Consider mixing keys từ Devise views vào devise.*.yml views. That's what Devise-i18n gem does, và tôi like it. Bạn làm như này:

# mixing the view scopes into devise.nl.yml
nl:
  devise:
    confirmations: ...
    registrations: ...
    edit: ...
    new: ...

Some Tweaks and Tips

  • Tôi không fan của header trong error message ('x errors prohibited this user from being saved'), nên removed that từ errors partial.
  • Nếu set default_locale to :nl, Rails sẽ 'humanize' keys nếu không find translation. Vậy t(:some_untranslated_key) show as Some Untranslated Key in view.
  • Với I18n-tasks gem bạn clean up unused keys và add missing keys. Great tool! Tuy nhiên, IDE của tôi có great i18n support và cho tôi quicker workflow than gem.

Parting Is Such Sweet Sorrow

Quick final word trước khi part. Khi bắt đầu journey này tôi không expect as much work as turned out to be. Tôi very happy now know where complexity comes from. Và future me và bạn now have list of all changes needed. Woohoo!

Nhưng even với checklist in hand, think before you act: maybe worth living with less optimal translations for a while…