Handling complex translation lookups in Rails
Let’s say you need to get I18n translations from different scopes depending on the logic, and only some of them are present in such overrides, while others need to fallback to the default scope. You build a logic like that:
But then you find out, that exists?
is not actually takes scope into the account at all (it always returning false
for any combination of key and scope). As when you look for implementation (good thing you can do cmd+B in RubyMine and go directly for the implementation), you see this call:
config.backend.exists?(locale, key, options)
. And when you go to the backend exist?
definition you see next:
So what can be a way out? (Don’t say monkey patching, you are going to regret that later) It’s actually quite simple, you have to use bang version of translate and catch exception from it: