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.

I’m Sheriff John Bunnell, most people don’t even think about law enforcement until they either do something wrong, or get wronged them self. But police know that fighting crime is a full time job. If something isn’t going down now, it will be soon and officers have to be ready. So get ready, what we’re going to show you tonight is the ruthlessness of criminals, the toughness of cops and the clash if both sides refuse to back down.