30 8 / 2012

Integrating Prefixr with Rails asset pipeline

Prefixr is cool online service created by Jeffrey Way for adding vendor prefixes to your css. It has nice and simple API to let you integrate it into your workflow. Here is how you can integrate it with Rails asset pipeline.

Just create prefixr.rb file inside config/initializers folder with following content:

require 'uri'
require 'net/http'

class PrefixrPostprocessor < ::Tilt::Template
  def prepare
  end

  def evaluate(context, locals, &block)
    uri = URI.parse "http://prefixr.com/api/index.php"
    Net::HTTP.post_form(uri, { css: data }).body
  end
end

Rails.application.assets.register_postprocessor 'text/css', PrefixrPostprocessor

It defines and registers postprocessor for text/css files. Now, every css file served through rails will be automatically prefixr’d! This will work even if you use sass or less!

The downside of this approach is that it will slow down the development because it will need to make HTTP request to prefixr.com API every time the css file is requested by browser. I wish that there is ruby version of prefixr service as a gem that I could just use directly inside PrefixrPostprocessor. That would be just awesome! Who knows.. maybe I just make one!