accessing ruby I18n locale messages from the web client

Categories Development, Fun, hack, Uncategorized, Working smart

I like to keep my client-side code completely decoupled from the server-side but I still want to keep one message source for localization.

The ruby stack I use includes Sinatra, Sinatra::I18n and the I18n gem for localization and this is the simplest and most effective way (that I’ve found) of accomplishing this:

The Sinatra route:
get '/locales/:locale_name/messages.js' do |locale_name|
    locale = locale_name.to_sym
     
    if I18n.available_locales.include? locale then
        messages = I18n.backend.send(:translations)
        "var m = " + messages[locale].to_json 
                    + "; t = function(k){ return eval('m.' + k); }";
    else
        not_found
    end
end 

This way the yml locale file is loaded and served and wrapped for quick use.

In the client just request the messages script and then when you need a message call t(‘message key’) just like you’d do it in ruby 🙂


var message = t('message.key');

Leave a Reply

Your email address will not be published. Required fields are marked *