Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

Introducing Babilu: Rails i18n for your JavaScript

Posted on February 02, 2009 12:48 Tagged with rails, javascript, i18n.

Babilu is a Rails plugin that mirrors your i18n setup in JSON and JavaScript format. This allows you to take your translations with you when you cross that great divide which separates the server from the browser. It provides a very similar environment that you can use in your JavaScript code to do translations directly in the browser.

I18n.defaultLocale // "en"
I18n.locale // Whatever the locale has been set to on the server

I18n.t('hello') // "Hello World"
I18n.t('messages.invalid', {scope:['activerecord', 'errors']})  // "is invalid"
I18n.t('activerecord.errors.template.header', {count:4, model:'horse'}) // "4 errors prohibited this horse from being 
saved"

//Defaults work the same way as in Rails
I18n.t('doesntexist', {defaultValue:'humbaba'}) // "humbaba"
I18n.t('doesntexist', {defaultValue:':hello'}) // "Hello world"
I18n.t('doesntexist', {defaultValue:[':alsodoesntexist', 'The Sasqutch: Fact or Fiction?']}) // "The Sasquatch: Fact or 
Fiction?"

To install:

script/plugin install git://github.com/toretore/lucy.git
script/plugin install git://github.com/toretore/babilu.git

Then load the generated JavaScript in your layout:

<head>
  <script type="text/javascript" src="/javascripts/locales.js"></script>
</head>

Babilu will automatically reload your locales on each request in development mode, just like you’d expect, but in production they will only be loaded when the server starts up.

He will bring to you a harvest of wealth, in the morning he will let loaves of bread shower down, and in the evening a rain of wheat!