In Rails, my reflex for putting an application in the visitor’s language is
an around_action in the base controller. It wraps every action in the
right locale, and one I18n serves the views, the models and the validation
messages alike:
around_action :switch_locale
def switch_locale(&action)
locale = params[:locale] || I18n.default_locale
I18n.with_locale(locale, &action)
end
The locale can come from a parameter, the Accept-Language header or a
stored preference, but the shape stays the same, and it is the shape the
Rails guide
shows.
This time the Hanami 3 companion app of this series, a small CTF challenge
tracker, has to answer in the visitor’s language. It has users but no stored
language preference, so it reads the browser’s Accept-Language header.
What I compare here is the mechanism around it.
Most of it works as in Rails
The i18n gem was already in the Gemfile from hanami new. When it is
bundled, Hanami registers an "i18n" component, reads the files under
config/i18n/, and gives templates and actions their t and l helpers.
Relative keys resolve the way they do in Rails: t(".empty") in
app/templates/challenges/index.html.erb is challenges.index.empty, in a
layout it is layouts.app.<key>, and in Actions::Sessions::Create it is
sessions.create.<key>. The first request spec asking for French passed
with nothing to diagnose.
Pluralisation also answers a question the
post on parts left with a
ternary. There is no pluralize helper, and the ternary goes away anyway:
count: picks the form from the translation’s one and other keys:
points:
one: "1 point"
other: "%{count} points"
def points_label
helpers.t("challenges.points", count: points)
end
A part reaches t through its helpers object, and with an absolute key,
since a relative key needs a template being rendered and a part spec has
none.
No around callback
The around_action has no equivalent. Hanami::Action has
before and after callbacks, and no around. That matters for exactly
this job, because the app’s locale is kept per thread: the
Hanami guide says so, and
recommends with_locale for setting it per request, since it restores the
previous value afterwards, even when the block raises.
The obvious substitute is a before callback that assigns the locale. Swap
one into the app, make one French request on a thread, and ask what the
thread speaks afterwards:
after a French request: app i18n :fr, global I18n :fr
Anything that runs on that thread outside an action would now speak French.
Inside an action, the callback also comes too late: Hanami validates the
params before it runs any before callback. Against the finished app, with
its French validation messages and the thread back in English, an empty
French submission renders:
<h1>Nouveau défi</h1>
<li>Nom must be filled</li>
<li>Catégorie must be filled</li>
The page is in French, and the validation messages are in whatever language
the previous request left on the thread. The method that wraps everything,
parameter validation included, is call itself, so the base action
overrides it:
def call(env)
locale = locale_for(env)
::I18n.with_locale(locale) { i18n.with_locale(locale) { super } }
end
private
def locale_for(env)
asked = ::Rack::Request.new(env).accept_language.reject { |_, quality| quality.zero? }
ranked = asked.sort_by.with_index { |(_, quality), index| [-quality, index] }
ranked.map { |tag, _| tag[0, 2].downcase.to_sym }.find { |locale| i18n.available_locales.include?(locale) } || i18n.default_locale
end
Rack parses the header, and locale_for ranks the languages by their q
weight, dropping any at zero. Same probe against this version:
after a French request: app i18n :en, global I18n :en
You will have noticed that call switches the locale twice. The next
section explains why.
Two translation backends
The validation messages needed translating too, and they would not follow:
name must be filled, with the browser asking for French. In Rails I would
add errors.messages.blank to fr.yml and be done, because there is one
I18n.
Hanami’s t does not read the global I18n. The app has its own backend
object, registered as "i18n", and the two do not share translations:
app backend: "Défis"
global I18n: "(missing)"
same backend? false
The validation messages come from dry-validation, which knows nothing about
Hanami’s backend. It uses dry-schema’s :i18n messages backend, which talks
to the global ::I18n directly (@t = ::I18n.method(:t) in dry-schema
1.16.0). The contract messages go under dry-validation’s own namespace,
which the app keeps in a second file, one entry per predicate. Its first
lines:
fr:
dry_validation:
errors:
key?: "est obligatoire"
filled?: "doit être renseigné"
It also means a second locale switch per request, because the global
::I18n.locale and the app backend’s locale are two different settings. That
is the double with_locale in call.
Keeping a backend per slice is defensible, since each slice can then carry its own translations. It is still a surprise the first time a library you did not write reaches for the other one.
A provider is not an initializer
dry-validation has to be told to use its :i18n backend before any action’s
params block builds a contract, since each contract copies its parent’s
settings when it is created. In Rails that is a file in
config/initializers/. The Hanami word that sounded closest was provider, so
my first attempt was this, reconstructed here because it did not survive:
Hanami.app.register_provider(:validation) do
prepare do
require "dry/validation"
Dry::Validation::Contract.config.messages.backend = :i18n
end
end
The spec still saw the YAML backend. A provider is a component with a lifecycle, and it runs when something resolves what it registers, or when the app boots. This one registers nothing. The test suite only prepares the app, so nothing ever started it:
after prepare: :yaml
after boot: :i18n
The booted case is the misleading one. A server boots the app through
config.ru, so the same file would have worked in development and
production while doing nothing under the specs: one file, two behaviours,
depending on how the process started.
I deleted it. dry-validation’s configuration guide recommends an abstract contract that the others inherit from, and that is what the app has now:
module CtfTracker
class Contract < Dry::Validation::Contract
config.messages.backend = :i18n
config.messages.load_paths << Hanami.app.root.join("config/errors.yml")
end
end
Hanami builds each action’s params contract on Dry::Validation::Contract
itself, so the base action overrides params to build on this one instead:
def self.params(klass = nil, &block)
super(klass || Class.new(CtfTracker::Contract) { params(&block) })
end
The ordering is guaranteed by inheritance rather than by a boot step, and
Dry::Validation::Contract itself is left untouched.
The first request of a fresh process
The suite was green. Out of habit, I made one request against a fresh process, and it failed:
GET /sign_in -> I18n::InvalidLocale: :en is not a valid locale
The global ::I18n knows no locale at all until something loads
translations into it, and with_locale(:en) refuses a locale it does not
know. A contract loads its messages when its schema is defined, which happens
when an action with a params block is loaded. So the first request only
works if a contract got there first:
POST /session -> 422
GET /sign_in -> 200
The suite gets there first without making a single request. A spec that
names an action class in its describe loads that action, and with it a
params block, while RSpec is still collecting examples. Without the fix,
and without the spec that came with it, the full suite says
117 examples, 0 failures, while the sign-in example run on its own fails
with the same InvalidLocale. A green run depended on which files happened to
be loaded. So the app got a spec that spawns a fresh process and makes exactly
that request, and it fails without the fix below.
The fix belongs where the two worlds can be introduced to each other: the moment the app’s i18n starts. Hanami lets you hook into its own provider rather than writing a new one:
Hanami.app.configure_provider(:i18n) do
after :start do
::I18n.available_locales = provider_container["i18n"].available_locales
end
end
My first version read target["i18n"] and failed with
key not found: "i18n". dry-system runs a step, then its after callbacks,
and only then copies the provider’s registrations into the app’s container,
so inside after :start the backend exists only in provider_container.
With that change, the fresh process answers GET /sign_in -> 200.
What French still costs
Error messages are built from a field name and a message, so the field name
has to be translated too. dry-validation can do that itself with
errors(full: true), but Hanami::Action::Params calls errors.to_h
without options, so the app keeps a fields table in each locale file and
prefixes the message itself. That works, with a catch any French speaker
will spot:

An empty submission, with the browser asking for French. “Catégorie” is
feminine, so the message should end in “renseignée”. The app keeps one
filled? message for every field, and that one is masculine.
The dates have the same flavour of cost. l(date, format: :long) gives
“1 March 2026” out of the box, because Hanami ships English date tables with
its provider. In Rails, the rails-i18n gem would bring the French ones. Here
the month and day names are written by hand in fr.yml.
The validation messages alone took an afternoon, most of it spent on the
two backends. What the green suite could not show was the first request: the
global ::I18n learns its locales from whatever loads first, and a test run
has always loaded something that a fresh process has not. The whole feature,
with the fresh-process spec, is at
09-two-i18n-worlds.
The comment at the top of that spec still gives an earlier explanation of
what loads the global ::I18n first; a
later commit
corrects it.
Comments, questions, or just a reaction?
Send an email to ~bounga/bounga.org-discuss@lists.sr.ht. It is public and archived, so other readers can follow along and answer too.