Open sander-deryckere opened 2 months ago
This is the monkey-patch I came up with to fix the behaviour:
nil
).module I18n
def self.with_locale(tmp_locale = nil)
if tmp_locale == nil
yield
else
current_locale = self.config.raw_locale
self.locale = tmp_locale
begin
yield
ensure
self.config.raw_locale = current_locale
end
end
end
class Config
def raw_locale
@locale
end
def raw_locale=(locale)
@locale = locale
end
end
end
What I tried to do
Background
In our project, we have certain translated masterdata that can be maintained by users. So the translation strings are stored in the database. But we want to use the current locale from
I18n
to render the correct strings, together with all the fixed translations.The default locale is set on the installation level, and can also be configured by an admin.
For this, we have a number of specs that test the difference between only a default locale being present, or a (when executed in the context of a user), the correct user-specific locale being used.
While running these specs, we noticed that after calling code in a
with_locale
block, the translations started to use wrong locales, and didn't respond to updates to thedefault_locale
setting.Conclusion
Apparently, the
default_locale
is stored aslocale
after running awith_locale
block, causing further modifications ofdefault_locale
to have no effect as long as the I18n class stays in memory.See the annotated sequence of setting locales at the bottom of the ticket.
What I expected to happen
I expected the
locale
to be reset to an empty value after thewith_locale
block was executed. So it would continue to render strings in thedefault_locale
, even if that value is updated.According to the documentation (https://guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests):
Since the system locale rarely changes, and the I18n object doesn't survive that long due to threading and containers, it's unlikely to affect our production environment. But it was an annoying spec failure to debug 😅 .
What actually happened
The old
default_locale
was stored aslocale
, making it impossible fordefault_locales
to have an effect.Versions of i18n, rails, and anything else you think is necessary
Latest
Bonus points for providing an application or a small code example which reproduces the issue.
Thanks! :heart: