Rails 7: Pass default values to I18n's `translate` method
source link: https://blog.saeloun.com/2021/12/01/rails-7-default-values-for-i18n-translate
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.
> ApplicationController.helpers.t('hello', default: "Hey there!")
=> "Hello world"
> ApplicationController.helpers.t('hi', default: "Hey there!")
=> "Hey there!"
Let’s now pass in a proc instead (using Rails 6.1.1),
> ApplicationController.helpers.t('hi', default: Proc.new { "Hey there!" })
=> #<Proc:0x000055d6898cc188@(irb):3>
However the same using I18n#t
works as expected,
> I18n.t('hi', default: Proc.new { "Hey there!" })
=> "Hey there!"
Let’s look at another example.
This time by passing a hash that needs resolutions via the :count
option.
> ApplicationController.helpers.t :count, default: { one: '1 bug', other: '%{count} bugs' }, count: 2
=> "1 bug"
This is wrong since the count
was passed as 2
.
The same works perfectly using I18n#t
,
> I18n.t :count, default: { one: '1 bug', other: '%{count} bugs' }, count: 2
=> "2 bugs"
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!
> ApplicationController.helpers.t :count, default: { one: '1 bug', other: '%{count} bugs' }, count: 2
=> "2 bugs"
Now, let’s try passing in a proc,
> ApplicationController.helpers.t('hi', default: Proc.new { "Hey there!" })
=> "Hey there!"
The translate
helper now passes default
values that aren’t translation keys through I18n.translate
for interpolation.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK