How to translate javascript strings in Rails – .js localization

Hi there!

Today i have achieved the configuration of a great gem that will help you to translate your javascript strings.

It is called

I was following the instructions but a couple of things did not work. Both in application.rb

1. Library

In the instructions it says to add the following line:

config.middleware.use I18n::JS::Middleware

But in my case it did not work. I searched and found this alternative:

config.middleware.use SimplesIdeias::I18n::Middleware

(Thanks for the hint here:

2. Configuration

I had to change this line

config.assets.initialize_on_precompile = false

and set it to true

config.assets.initialize_on_precompile = true

3. Inform js of the current locale
Another important thing I had to do was to add a couple of lines to the application.html.erb

I18n.defaultLocale = "";
I18n.locale = "";

And then it started working nicely.

As an example, in the .js file I put

var alertMsg = I18n.t('posts.alert');

And that corresponds to

alert: "Alert message"

How this works internally I am not sure. I have realised that the key file is translations.js that is automatically created under public/assets

Translations.js gets automatically updated, and you can also update it manually with:

$ rake i18n:js:export

I have also evidenced that the Rails cache can spoil the party. So if you notice erratic behaviour do clear the cache:

rake tmp:clear (I have had similar issues in the past…)

Hope it helped! Thanks to Nando Vieira for the amazing work!

Delete the cache in Rails

I was trying to fix an issue with a css style in Rails. It was driving me nuts. It came from an installed gem, so probably it was deeply rooted in the cache system of Rails. Then I got some help saying that I should clear the cache:

rake tmp:clear

I did it and solved the issue!