DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on • Updated on

I18n in Rails

πŸ“— Translate Active Record

1. Define the dictionary at some yml files

The file name is not related. The term at the second level activerecord: works.

#config/locales/models_ja.yml
#config/locales/activerecords_ja.yml
#...etc

ja:
  activerecored:
    models:
      author: θ‘—θ€…
    attributes:
      author:
        name: 名前
        description: 概要

2. Use it in ERB

<div>
  <%= Author.model_name.human %>
  <%= Author.human_attribute_name :name %>
  <%= Author.human_attribute_name :description %>
</div>

πŸ“— Translate any words

1. Define the dictionary at some yml files

  • 😎 You can write words in split multiple files.
  • 😎 You can write words with parameter, see also mail.registration_thanks.name_sir.
  • 😎 You can write an array of words, see also date.day_names.
# config/locales/words.ja.yml
ja:
  labels:
    profile: プロフィール
  messages:
    sending: 送俑中
    error: γ‚¨γƒ©γƒΌγŒη™Ίη”Ÿγ—γΎγ—γŸ
  mail:
    registration:
      subject: "γ”η™»ιŒ²γ‚γ‚ŠγŒγ¨γ†γ”γ–γ„γΎγ™πŸŽ‰ %{name}様"

# config/locales/words.ja.yml
ja:
  date:
    day_names:
    - ζ—₯
    - 月
    - 火
    - ζ°΄
    - 木
    - 金
    - 土

2. Use it

<%= label_tag t('labels.profile') %>

<p><%= t('messages.sending') %></p>
# class RegistMailer < ApplicationMailer
@user.name = n350071
subject = I18n.t('mail.registration.subject', name: @user.name)
subject = I18n.t(:subject, scope: 'mail.registration', name: @user.name)

# => "γ”η™»ιŒ²γ‚γ‚ŠγŒγ¨γ†γ”γ–γ„γΎγ™πŸŽ‰ n350071様
# => "γ”η™»ιŒ²γ‚γ‚ŠγŒγ¨γ†γ”γ–γ„γΎγ™πŸŽ‰ n350071様
I18n.t('date.day_names')
# => "[\"ζ—₯\", \"月\", \"火\", \"ζ°΄\", \"木\", \"金\", \"土\"]"

πŸ“— Localize Format

The formats reference.

Set your formats

en:
  date:
    formats:
      default: ! '%Y/%m/%d'
      long: ! '%Y/%m/%d/(%a)'
      short: ! '%m/%d'
      middle: ! '%b %d %a'
<%= l(@event.start_date, format: :middle) %>
#=> 'Nov 15 Fri'

default

<%=l Time.now, format: :short %>
I18n.l(Time.now, format: :short) #=> "2019/11/12 10:21"
I18n.l(Time.now, format: :long)  #=> "2019εΉ΄11月12ζ—₯(火) 10ζ™‚21εˆ†41η§’ +0900"

πŸ”— Parent Note

Top comments (0)