RACK

Rack is a modular interface for handling web requests, written in Ruby, with support
for many different web servers. It abstracts away the handling of HTTP requests and
responses into a single, simple call method that can be used by anything from a plain
Ruby script all the way to Rails itself.

 

Listing 2.1 HelloWorld as a Rack application
class HelloWorld
def call(env)
[200, {“Content-Type” => “text/plain”}, [“Hello world!”]]
end
end

 
An HTTP request invokes the call method and passes in a hash of environment variables,
akin to the way that CGI works. The call method should return a three-element array
consisting of the status, a hash of response headers, and finally, the body of the request.
As of Rails 2.3, request handling was moved to Rack and the concept of middleware
was introduced. Classes that satisfy Rack’s call interface can be chained together as filters.
Rack itself includes a number of useful filter classes that do things such as logging and
exception handling.
Rails 3 was re-architected from the ground up to fully leverage Rack filters in a
modular and extensible manner. A full explanation of Rails’ Rack underpinnings is
not essential, especially since Rack does not really play a part in day-to-
day development of applications. However, it is essential Rails 3 knowledge to understand
that much of Action Controller is implemented as Rack middleware modules. Want to
see which Rack filters are enabled for your Rails 3 application? There’s a rake task for
that!

 

$ rake middleware