Dictionaries
A dictionary is a YAML file under config/locales/ (subdirectories too)
whose first key is a locale: en, ja, pt-BR. cybertrain new writes
config/locales/en.yml; add a file per language and list the languages in
config/app.rb.
ja:
activerecord:
models:
article: "記事"
attributes:
article:
title: "タイトル"
body: "本文"
articles:
index:
title: "記事"
count:
other: "%{number}件の記事"
Cybertrain.configure do |c|
c.i18n_available_locales = [:en, :ja]
end
spin run gen reads every *.yml under config/locales/ and compiles
them into gen/locales.rb, so the program carries its texts and reads no
YAML when it runs; the development server regenerates it when a dictionary
changes, and spin run gen -- --check reports it stale. Files are read in
path order, and a key in a later file replaces the same key in an earlier
one. A key that is a mapping in one file and a text or a list in another
stops gen, naming both files and lines.
The YAML gen reads
gen reads YAML with a reader of its own, which accepts what dictionaries use and refuses the rest with the file and line:
- Accepted: nested mappings; plain,
'single'and"double"quoted values on one line (\n,\t,\",\\,\uXXXX);|and>blocks; lists of values, as block items (also at their key's indentation, as rails-i18n writes them) or[a, b]; comments, a leading---, a BOM and CRLF line ends;~,nullor nothing for an empty text. - Every value is kept as text:
3is"3",nois"no",:yearis":year". - Refused: anchors and aliases, tags, a second document,
{a: b}mappings, quoted keys, a duplicate key, a tab in indentation, a list item that is not a value, a first key that is not a locale name, and a plain or quoted value that continues on the next line (write it with|or>).
Looking up text
t in a template, t in a controller and I18n.t anywhere else answer the
text at a key in the current locale:
I18n.t("greeting", name: "Ann") # "Hello, %{name}" => "Hello, Ann"
I18n.t("nope", default: "Nothing") # a String, or a Symbol naming another key
I18n.t("greeting", name: "Ann", locale: :ja)
I18n.translate_list("date.abbr_day_names") # => ["Sun", "Mon", ...]
Every option other than default:, count:, count_text: and locale:
fills the %{name} of its name; %% is a literal %, so %%{x} gives
%{x}, and a %{x} with no value raises
I18n::MissingInterpolationArgument. A key not found in the current locale
is looked up in the default locale. Lists, such as day and month names,
come from I18n.translate_list, since t always answers a String.
Counts and plural forms
count: (an Integer) picks a form under the key and fills %{count}:
zero for 0 when the key has one, else the locale's category, else
other.
| Language | Categories |
|---|---|
| English, and every language not listed | one for 1, else other |
| French | one for 0 and 1, many for a non-zero multiple of 1,000,000, else other |
| Russian | one (1, 21, 101), few (2 to 4, 22 to 24), else many |
| Japanese, Chinese | other |
A region uses its language's rule (pt-BR is pt's). count_text: fills
%{count} with a String without choosing a form, as the numericality
messages do with their limits.
Lazy lookup
A key starting with . is relative. In a template it is read under the
template's own path, as in Rails:
| Template | t(".title") reads |
|---|---|
app/views/posts/index.html.erb |
posts.index.title |
app/views/posts/new.html.erb, also when create renders it |
posts.new.title |
app/views/posts/_form.html.erb |
posts.form.title |
app/views/layouts/application.html.erb |
layouts.application.title |
app/views/__components/card_component.html.erb |
card_component.title |
app/views/mail/_password_reset.html.erb |
mail.password_reset.title |
In a controller, t(".created") in Admin::PostsController#create reads
admin.posts.create.created.
HTML in a text
A key ending in _html (or .html) is HTML: the template prints it as it
is, and escapes every value interpolated into it (a SafeString value
stays as it is). Any other text is escaped.
<%= t(".intro_html", name: @user.name) %> <%# "Hello <b>%{name}</b>": the name is escaped, <b> is not %>
Dates and times
l in a template and I18n.l format a Time or a Date with the locale's
time.formats or date.formats:
I18n.l(Time.utc(2026, 11, 10, 9, 5), format: :long) # => "November 10, 2026 09:05"
I18n.l(Date.new(2026, 11, 10), locale: :ja) # => "2026/11/10"
I18n.l(Time.utc(2026, 11, 10, 9, 5), format: "%a %p", locale: :ja) # => "火 午前"
format: is a format name (:default when not given, :short, :long,
or any other the dictionaries hold) or a pattern. %a %A %b %B take the
dictionary's day and month names and %p %P its time.am / time.pm
(also with ^, %^B); the rest is strftime's, formatted one directive at
a time as time_tag does (an unknown directive raises). A name directive
with another flag or a width (%-A, %10B, %#b) is strftime's too, so
it prints the English name; rails-i18n's formats use none. A format name no dictionary holds raises
I18n::MissingTranslationData. A Time is shown in the application's
zone, or in another with zone: "America/New_York"
(Time zones).
Choosing the locale
Every request starts at the default locale (config.i18n_default_locale,
:en, or CYBERTRAIN_I18N_DEFAULT_LOCALE). An application changes it in a
before_action, as examples/blog does: a ?locale= parameter, which is
then kept in a cookie, else the cookie, else the browser's
Accept-Language.
class ApplicationController < Cybertrain::Controller
before_action :set_locale
private
def set_locale
param = params[:locale]
if I18n.locale_available?(param)
I18n.locale = param
cookies[:locale] = param.to_s
return nil
end
stored = cookies[:locale]
if I18n.locale_available?(stored)
I18n.locale = stored
return nil
end
I18n.locale = request.preferred_locale(I18n.available_locales)
nil
end
end
I18n.localebelongs to the thread serving the request, so requests served at the same time keep their own; the framework puts it back to the default before every request and every action, and before every job and scheduled task a worker thread runs, so a job that sets it (a notice in its user's language) leaves the next job on that thread at the default.I18n.with_localesays the same thing in a block.I18n.locale = valuetakes a Symbol or a String and accepts only a name inconfig.i18n_available_locales(the default locale alone when that is empty); any other raisesI18n::InvalidLocale. It compares names and never turns request text into a Symbol, so a parameter can be passed as it is onceI18n.locale_available?said yes.request.preferred_locale(available)readsAccept-Languageby q-value, then order, matches a full tag before its language (ja-JPgives:ja) and answers an element ofavailable, or the default locale when nothing matches.I18n.with_locale(:ja) { ... }runs a block in another locale and puts the previous one back, also when the block raises: a mail to a user in their language, say.
A mail built in a request, or a broadcast rendered there, is in that request's locale.
Models and validation messages
A validation message is looked up when the validator runs, in the current
locale, along Rails' keys: activerecord.errors.models.<model>.attributes.<attr>.<type>,
activerecord.errors.models.<model>.<type>,
activerecord.errors.messages.<type>, errors.attributes.<attr>.<type>,
then errors.messages.<type>, where the bundled texts are. A message: on
the validation line still wins. A text can use %{attribute}, %{model},
%{count} and, as in Rails, %{value}, the attribute's value
("%{value} is already taken").
errors.full_messages joins the attribute's name and the message with
errors.format ("%{attribute} %{message}"; Japanese writes no space), and
a message on :base stands alone. The attribute's name is
Post.human_attribute_name(:title), which gen writes for every model:
activerecord.attributes.post.title, else the attribute humanised
(author_id gives "Author"). I18n.human_model_name("post") reads
activerecord.models.post (its one: form when it has plural forms), else
the key's last segment humanised ("admin/post" gives "Post"). There is no
Post.model_name.human.
The form builder reads the same names: f.label :title is
helpers.label.<form scope>.title, else human_attribute_name, and
f.submit is helpers.submit.create or update with the model's name
(en "Create Article"; rails-i18n's ja is "登録する", without the name).
Helpers that follow the locale
- The number helpers in a template read the locale's
number.*: the separators,number_to_currency's unit and format (ja"1,234円"), and the units ofnumber_to_humanandnumber_to_human_size. An option given in the call wins. A setting that neither the current nor the default locale holds is the English one, as Rails' helpers fall back to their defaults: an application whose default locale has nonumber.*keys still prints1,234.5and$12.50, never a number without its separators.Cybertrain::NumberHelpercalled from Ruby keeps English defaults. time_tagwith a format name, or withoutformat:, goes throughl; a pattern String keeps strftime's English names.time_ago_in_wordsanddistance_of_time_in_wordsreaddatetime.distance_in_words("2分").pluralizeuses the English inflector only when the locale is English; elsewhere the word is kept unless a plural is given.paginate's links, the jobs page and the submit button without a model readcybertrain.*keys, which an application can override as any other.
Missing keys
A key found in neither the current locale nor the default one answers:
| Where | Outside production (development, test, staging) | Production |
|---|---|---|
I18n.t, a controller's t |
"translation missing: ja.foo.bar" |
"Bar", the last segment humanised |
a template's t |
<span class="translation_missing" title="translation missing: ja.foo.bar">Bar</span> |
Bar |
config.i18n_raise_on_missing = true raises I18n::MissingTranslationData
instead, everywhere; a default: still answers first. examples/blog sets it
in its tests (c.i18n_raise_on_missing = true if c.test?), so a key missing
from both dictionaries fails a test rather than printing a marker.
The bundled dictionaries
The framework ships English and Japanese dictionaries
(cybertrain/locales/en.yml and
ja.yml): rails-i18n's keys for what the
framework uses (validation messages, date, time,
datetime.distance_in_words, number, helpers.submit,
errors.template), its own keys under cybertrain., and every text of the
screens cybertrain generate authentication writes (sessions.new.title,
passwords.create.sent, the mails' keys, activerecord.attributes.user).
An application's key overrides the bundled key of the same name, in that
locale. Plural forms merge: an application that writes only
datetime.distance_in_words.x_days.zero: "today" keeps the bundled one
and other. To change the sign-in page's title, or to translate the
screens into a third language, write their keys in config/locales/. In
a locale with no bundled dictionary, a key the application does not have
falls back to the default locale's text (the bundled English when the
default is en).