Introducing Ruby Gem I18nLazyScope26 Jan 2015
Lately, I’ve been working on some projects that require internationalization. I find it annoying to have to type
namespace.key each time I translate something. I can use lazy lookup1–
t('.key')–but it defaults to
locale.resource.key, which is not always desirable.
Wouldn’t it be nice if I could use lazy lookup and have granular control over the namespace? So, for example, if I typed
users#show the scope would default to
So, to have my cake and eat it, I wrote I18nLazyLookup. It lets you use lazy lookup with custom scopes.
How does it work?
The library inserts a customisable namespace in the scope between the
locale and the
resource keys. The following table shows the differences (in bold) between I18nLazyLookup and i18n-rails.
Tell me more
Say you are in
users_controller#show and you want to flash a welcome message.
Here, the scope for
welcome_message defaults to
en, the top level namespace. This is not a good way to structure locale files, and they’ll soon become messy and unmanagable. It’s better to scope them under a namespace.
This is better, but it’s a lot to type. It would be nice if we could write
t('.welcome_msg'), but we can’t because rails-I18n scopes the translation to
en.users.create.welcome_msg. Our controller namespace is missing.
And that’s where I18nLazyLookup helps. It lets you use lazy lookup with custom namespaces. This makes changing the structure of translations easy.
If the defaults don’t work for you, you can customise the namespaces with an initializer.
The namespaces now resolve according to the following table.
Check out the project repo on Github for more details.