There’s a lot of talk about Rack, but unless you’re a framework author yourself, you rarely see it. So what is Rack? And why, as an application developer, should you care about it?
Rack is a kind of middleware. It sits between your web application and the web server. It handles all of the server-specific API calls, passes on the HTTP request and all the environment parameters in a hash, and gives your application’s response back to the server. In other words, your application doesn’t need to know how to talk to an HTTP server, it needs to know how to talk to Rack.
This has a number of advantages. First, talking to Rack is easy (as you’ll see below). Second, since you only need to know how to talk to Rack, and Rack knows how to talk to many different HTTP servers, your application will run on any of these HTTP servers. Rack is like a universal adapter for web applications.
The Rack applications themselves are nothing special. In fact, the Rack API is so dead simple, it can be described in a single sentence:
A Rack application is any Ruby object that responds to the call method, takes a single hash parameter and returns an array containing the response status code, HTTP response headers and the response body as an array of strings.
That’s pretty much it. It sounds too simple to be true, or at least too simple to be useful, but when it really comes down to it, that’s all you’re really doing when you’re talking to HTTP servers.
But on to the real question: Why, as an application programmer, should you care about Rack? Well first, there’s always enlightenment in understanding how your framework works. But more importantly, there are useful things you can do with Rack. Most importantly: middleware.
Now this sounds a bit odd. But an extra layer between your application and Rack can be a good thing, and implement features that would only clutter your application. What this middleware does is simply take the request from Rack, pass it on to your application, get its response, add something to it or filter it or something along these lines and then pass the response back to Rack. This can be used to implement very interesting little features like a server-agnostic logger, or a request sanity checker, or a little middleware that emails an admin every time your application comes back with a 404. None of these features need to clutter up your application, they can be implemented as middleware with Rack.