Rails provides fantastic internationalization options with its I18n library.
However,
its translate
method sometimes behaves unpredictably.
Fortunately,
Rails 7 irons out of most of those irregularities.
Before
I18n’s #translate
method behaves differently when different default values are passed to it.
This inconsistency led to unexpected problems.
Let’s look at some examples!
I18n’s translate method accepts a default
parameter which returns this
value when the translation key is not found.
Below we can see it in action.
There is a key called hello
in our en.yml
file,
but the hi
key is missing.
This is how the default
parameter handles this situation.
Let’s now pass in a proc instead (using Rails 6.1.1),
However the same using I18n#t
works as expected,
Let’s look at another example.
This time by passing a hash that needs resolutions via the :count
option.
This is wrong since the count
was passed as 2
.
The same works perfectly using I18n#t
,
After
Thanks to this PR,
a default value can be a string that needs interpolation,
a hash that needs resolution via the :count
option,
or a Proc that needs evaluation.
It just works!
Now, let’s try passing in a proc,
The translate
helper now passes default
values that aren’t translation keys through I18n.translate
for interpolation.