Simple Rack application for JavaScript I18n

I tried to improve my old javascript_i18n gem recently, and I stumbled upon Kelly Redding’s rack-sprockets gem. I really like the idea of putting such stuff into Rack middleware stack – it doesn’t mess up your application, and it becomes framework agnostic. Then I realized that it can be made even simpler using Rack::Builder and utilities from rack-contrib repository. The following Rack application works with default Rails’ I18n backend:

The application serves JavaScripts, containing translations for the requested language, and stores them in the I18n.translations property. You can easily mount it using Rack::Builder in your config.ru file.

Now you can include the JavaScript in your application using ordinary script tag or javascript_include_tag helper:

If you need to cache JavaScript translations in the production environment, you can use Rack::ResponseCache to do that.

Rack::ResponseCache works very similar to Rails’ page caching – it stores responses in the given directory (public/javascripts/i18n).

The solution works great in Rails 3 applications, as well in the other frameworks with Rack::Builder available. If you need to use it in Rails 2, you should probably check out the Rack::SimpleEndpoint middleware. SimpleEndpoint can easily turn any Rack application into middleware, that you can mount in your Rails 2 app.