decodeURI

Creating a Rack Middleware for Minifying Your Javascript files

Posted in Uncategorized by lucianopanaro on October 15, 2008

If you are in the Ruby world you have probably heard of Rack. If you haven’t, and you are a Pythonista, then you only need to know that Rack is a sort of “WSGI for Ruby”. And in case you don’t know what Rack or WSGI are, then here’s a brief description:

“Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.”

So you can think of Rack as a “frameworks framework“. Merb and other ruby frameworks already support Rack, which means that they can share the middleware described above.

Creating a Rack Middleware

So let’s say you want your application (built on Rails, Merb, Ramaze or even Rack) to intercept any request for javascript files so that you can first minify them. Below is the sample code for achieving this with a Rack Middleware:

(You can checkout this code, its spec and example from http://github.com/lucianopanaro/rack-javascript-minifier. The javascript minifier is a port from Douglas Crockford’s library done by Ryan Grove.)

  class JavascriptMinifier
    F = ::File

    def initialize(app, path)
      @app = app
      @root = F.expand_path(path)
      raise "Provided path #{@root} does not exist" unless F.directory?(@root)
    end

    def call(env)
      path = F.join(@root, Utils.unescape(env["PATH_INFO"]))

      unless path.match(/.*\/(\w+\.js)$/) and F.file?(path)
        return @app.call(env)
      end

      if env["PATH_INFO"].include?("..") or !F.readable?(path)
        body = "Forbidden\n"
        size = body.respond_to?(:bytesize) ? body.bytesize : body.size
        return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
      end

      last_modified = F.mtime(path)
      min_path = F.join(@root, "m_#{last_modified.to_i}_#{F.basename(path)}")

      unless F.file?(min_path)
        F.open(path, "r") { |file|
          F.open(min_path, "w") { |f| f.puts JSMin.minify(file) }
        }
      end

      [200, {
             "Last-Modified"  => F.mtime(min_path).httpdate,
             "Content-Type"   => "text/javascript",
             "Content-Length" => F.size(min_path).to_s
            }, F.new(min_path, "r")]
    end
  end

Rack Middleware’s interface is dead simple. As Marc-André Cournoyer points out: “It must have a call method and receive a Rack app as the first argument of new”.

So here, when we initialize the JavascriptMinifier, we pass the root path where the javascript files are placed. Every time it gets called, the middleware first checks if the request is for a javascript file. If it’s not, it passes it to the application. If the request is for a javascript in a parent directory, then we return a forbidden (403) page. Finally, if the request passes these filters, the middleware creates a minified version of the javascript file and returns it.

Running your application with middleware

This is also really simple using Rack::Builder:

“Rack::Builder implements a small DSL to iteratively construct Rack applications. use adds a middleware to the stack, run dispatches to an application.”

So here is an example of a rackup file that you can use to startup your application with some middleware:

   use Rack::CommonLogger
   use Rack::ShowExceptions
   use JavascriptMinifier, "./"
   run Rack::Lobster.new

Testing and Spec’ing helpers

Rack provides two helpers that will be of great use for testing your application: Rack::MockRequest and Rack::MockResponse, so you have no excuses to test your Rack Middleware and do some TDD/BDD!

Where to go from here

To learn how to develop your own Rack Middleware, your best resource will be Rack sources. You will learn a lot of Rack (and Ruby in general) by reading the code and specs they provide: URLMap, CommonLogger, File. There also is a group where you can ask your questions too.

So enjoy your trip with Rack Middleware and feel free to comment your thoughts and questions!

Advertisements
Tagged with: , , ,

2 Responses

Subscribe to comments with RSS.

  1. Jonathan Soeder said, on December 16, 2008 at 6:17 pm

    Luciano,

    Thanks for the idea. I have been writing a web application using the ExtJS framework and what I do before deploying the application to production is combine all of my individual class files into a single file, then minify them, and in the production environment I just refer to the compressed file…

    Are there any advantages to running the minification step at the request level?

    In either case , you’ve given me a bunch of ideas to try out Rack. thanks

    • luciano.panaro said, on December 17, 2008 at 5:17 am

      Hey Jonathan,

      Glad you liked it :). The idea was to show how simple is to create a piece of middleware. I follow the same approach you are, and I honestly wouldn’t use this in production.

      Anyways, you can check out http://github.com/rtomayko/rack-contrib/ where there are more interesting and useful pieces of middleware 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: