The Blog

I18n power tool: stylesheet_flipper for rails’ asset pipeline

Spice up your localization toolbox with stylesheet_flipper: Make you left-to-right (LTR) designed css stylesheets support right-to-left (RTL) locales with a snap (and vice versa).

For the impatient: All this ended up as a gem, that you can find on rubygems and on github.

Background
In my most recent startup, monibuds, we recently saw an opertunity to enter the Israeli market after having built our app for english and danish locales. But maintaining two sets of stylesheets, one for LTR and one for RTL seemed like a mess, so I started looking for better solutions. I wanted, using rails’ asset pipeline (sprockets), to enable right-to-left locales as well as left-to-right, but I only wanted to maintain a single set of stylesheets.

Solution
By building a railtie that registers a sprockets bundle_processor, you can hook into the asset pipeline and process any asset both on-the-fly (development) and during assets:precompile (production). Like this:

module StylesheetFlipper
  class Railtie < Rails::Railtie
    initializer "stylesheet_flipper.initialize_rails", :group => :assets do |app|
      app.assets.register_bundle_processor 'text/css', :stylesheet_flipper do |context, data|
        if context.logical_path.include?('-flipped')
          R2.r2 data
        else
          data
        end
      end
    end
  end
end

Then you only need to serve the stylesheet with the ‘-flipped’ postfix when you want to flip it. To do that takes a few steps:

app/assets/stylesheets/application-flipped.css

/*
 *= require application
*/

app/helpers/application_helper.rb

def stylesheet_flipper
  if [:ar, :he].include? I18n.locale
    "application-flipped"
  else
    "application"
  end
end

app/views/layouts/application.html.erb

<%= stylesheet_link_tag stylesheet_flipper %>

config/environments/development.rb

# for flipped versions to work, we need to bundle
# the stylesheet in dev mode as well
config.assets.debug = false

config/environments/production.rb

config.assets.precompile += %w( application-flipped.css )

Oh, and dont forget to add a direction to you body tag if you don’t have one
app/assets/stylesheets/application.css

body {
  direction: ltr;
}

Et voila. Happy flipping!

Leave a Comment

Let us know your thoughts on this post but remember to place nicely folks!