Three Things I Learned This Week - November 18 2016

I’ve been working a bit with Rails Internationalization (I18n) this week, here’s what I learned:

  • Many gems will add their own I18n locale translations. If you want to see all locales currently loaded in a given Rails environment, you can use the command: I18n.load_path. This command is also helpful in a debugging context to verify that files you have added are being recognized. By default, Rails only loads the locale files at the root of config/locales. If you want to organize your locales into directories, you need to configure Rails (config/application.rb.) to look deeper with:
config.i18n.load_path += Dir[Rails.root.join("config", "locales", "**", "*.{rb,yml}")]
  • Rails uses convention over configuration with respect to I18n too. If your translation keys match your view directory structure, you can just pass the key prepended with a “.” to the translate helper, instead of the whole chain. For example, to translate values in /views/users/index.html.erb, I can simply use t(".hi_there") instead of t("users.index.hi_there").
  • Translations are html escaped automatically, helping to prevent XSS vulnerabilities with your content. If you want html markup in your translation, giving the translation key a suffix of _html will prevent the content from being html escaped, similar to using the .html_safe view helper. For example, I could create the key hi_there_html: "<strong>Hi there</strong>", and it would correctly display my markup.

The Rails Guides on Internationalization have really good information on I18n, if you haven’t read through it, it’s worth a quick read, I bet you’ll pick up a thing or two.