Scroll to top
6 min read

If you're a Ruby programmer who has done any kind of web development, you've almost certainly used Rack, whether you know it or not, as it's the foundation which most Ruby web frameworks (Rails, Sinatra, etc.) are built upon. Let's dig into some of the basic concepts of Rack and even build a small app or two.


What Is Rack, Exactly?

Rack is several things, actually:

  • a web server interface
  • a protocol for building and composing web applications
  • a collection of middleware utilities

A Web Server Interface

Part of what's nice about Rack, is that it provides a standardized way for Ruby applications to talk to web servers, abstracting away the server stuff (listening on a port, accepting connections, parsing HTTP requests and responses, etc.) so that you can focus on what your application does.


The Protocol

The Rack protocol is very simple: a Rack application is simply a Ruby object with a call method. That method should accept an environment hash describing the incoming request and return a three-element array in the form of: [status, headers, body], where:

  • status is the HTTP status code.
  • headers is a hash of HTTP headers for the response.
  • body is the actual body of the response (e.g. the HTML you want to
    display). The body must also respond to each.

The easiest way to understand Rack's protocol, is by taking a look at some code.

First, get the rack gem and set up a directory:

1
2
$ gem install rack
3
$ mkdir hellorack
4
$ cd hellorack

Now create a file named config.ru and fill it in with the following:

1
2
class Hello
3
  def self.call(env)
4
    [ 200,                              # 200 indicates success

5
      {"Content-Type" => "text/plain"}, # the hash of headers

6
      ["Hello from Rack!"]              # we wrap the body in an Array so

7
                                        # that it responds to `each`

8
    ]
9
  end
10
end
11
12
# Tell Rack what to run our app

13
run Hello

Save the file, open up your terminal and run the rackup command:

1
2
$ rackup
3
[2012-12-21 17:48:38] INFO  WEBrick 1.3.1
4
[2012-12-21 17:48:38] INFO  ruby 1.9.2 (2011-07-09) [x86_64-darwin11.0.1]
5
[2012-12-21 17:48:38] INFO  WEBrick::HTTPServer#start: pid=1597 port=9292

The bottom few lines of output, in the above code, let you know that Rack is running your app at port 9292 using Ruby's built-in WEBrick web server. Point your browser to http://localhost:9292 to see a happy welcome message from Rack.

Kill the app (ctrl-c) and let's talk about what is going on here.

When you run the rackup command, Rack looks for a rackup config file (conventionally named config.ru, but you can name it whatever you want). It then starts a web server (WEBrick by default) and runs your app.

This protocol is the foundation on which popular frameworks like Rails and Sinatra are built. What they do is layer functionality like template rendering, route dispatching, managing database connections, content negotiation, etc. on top of this fundamental abstraction.

How they do this, is what brings us to the concept of middleware.


Middleware

Middleware gives you a way to compose Rack applications together.

A middleware (yes, it's both singular and plural) is simply a Rack application that gets initialized with another Rack application. You can define different middleware to do different jobs and then stack them together to do useful things.

For example, if you have a Rails app lying around (chances are, if you're a Ruby developer, that you do), you can cd into the app and run the command rake middleware to see what middleware Rails is using:

1
2
$ cd my-rails-app
3
$ rake middleware
4
use ActionDispatch::Static
5
use Rack::Lock
6
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007fcc4481ae08>

7
use Rack::Runtime
8
use Rack::MethodOverride
9
use ActionDispatch::RequestId
10
use Rails::Rack::Logger
11
use ActionDispatch::ShowExceptions
12
use ActionDispatch::DebugExceptions
13
use ActionDispatch::RemoteIp
14
use ActionDispatch::Reloader
15
use ActionDispatch::Callbacks
16
use ActiveRecord::ConnectionAdapters::ConnectionManagement
17
use ActiveRecord::QueryCache
18
use ActionDispatch::Cookies
19
use ActionDispatch::Session::CookieStore
20
use ActionDispatch::Flash
21
use ActionDispatch::ParamsParser
22
use ActionDispatch::Head
23
use Rack::ConditionalGet
24
use Rack::ETag
25
use ActionDispatch::BestStandardsSupport
26
run MyRailsApp::Application.routes

Every request that comes into this app starts at the top of this stack, bubbles its way down, hits the router at the bottom, which dispatches to a controller that generates some kind of response (usually some HTML), which then bubbles its way back up through the stack before being sent back to the browser.


A Middleware Example

Nothing fosters understanding a new concept like coding does, so let's build a very simple middleware that just converts the response body to uppercase. Open up our config.ru file from before and add the following:

1
2
class ToUpper
3
  # Our class will be initialize with another Rack app

4
  def initialize(app)
5
    @app = app
6
  end
7
8
  def call(env)
9
    # First, call `@app`

10
    status, headers, body  = @app.call(env)
11
12
    # Iterate through the body, upcasing each chunk

13
    upcased_body = body.map { |chunk| chunk.upcase }
14
15
    # Pass our new body on through

16
    [status, headers, upcased_body]
17
  end
18
end
19
20
# This is the same Hello app from before, just without all the comments

21
class Hello
22
  def self.call(env)
23
    [ 200, {"Content-Type" => "text/plain"}, ["Hello from Rack!"] ]
24
  end
25
end
26
27
use ToUpper # Tell Rack to use our newly-minted middleware

28
run Hello

Run the rackup command again and visit http://localhost:9292 to see our new middleware in action.

What Rack did here was build a Rack application that was the composition of the ToUpper and Hello applications. Internal to Rack, there's a Builder class that effectively constructed a new app by doing the equivalent of:

1
2
app = ToUpper.new(Hello)
3
run app

If there were more middleware present (like in the Rails stack), it would just nest them all the way down:

1
2
use Middleware1
3
use Middleware2
4
use Middleware3
5
run MyApp
6
7
#=> Boils down to Middleware1.new(Middleware2.new(Middleware3.new(MyApp)))

Request and Response Classes

When you start writing Rack applications and middleware, manipulating the [status, headers, body] array quickly becomes tedious.

Rack provides a couple of convenience classes, Rack::Request and Rack::Response, to make life a little bit easier.

Rack::Request wraps an env hash and provides you with convenience methods for pulling out the information you might need:

1
2
def call(env)
3
  req = Rack::Request.new(env)
4
  req.request_method #=> GET, POST, PUT, etc.

5
  req.get?           # is this a GET requestion

6
  req.path_info      # the path this request came in on

7
  req.session        # access to the session object, if using the

8
  # Rack::Session middleware

9
  req.params         # a hash of merged GET and POST params, useful for

10
  # pulling values out of a query string

11
12
  # ... and many more

13
end

Rack::Response is complementary to Rack::Request, and gives you a more convenient way to construct a response. For example, our Hello app could be rewritten as follows:

1
2
class Hello
3
  def self.call(env)
4
    res = Rack::Response.new
5
6
    # This will automatically set the Content-Length header for you

7
    res.write "Hello from Rack!"
8
9
    # returns the standard [status, headers, body] array

10
    res.finish
11
12
    # You can get/set headers with square bracket syntax:

13
    #   res["Content-Type"] = "text/plain"

14
15
    # You can set and delete cookies

16
    #   res.set_cookie("user_id", 1)

17
    #   res.delete_cookie("user_id")

18
  end
19
end

Conclusion

In this article, we've covered the basic concepts of Rack, which should be enough for you to get a better understanding of what's under the hood of the many popular frameworks out there and also help you get your feet wet if you're interested in developing directly with Rack.

Code is an excellent teacher, and so if you're interested in Rack, I highly recommend looking at its source. It comes with a lot of very useful baked-in utilities and middleware (and plenty more at rack-contrib) that you can use and learn from.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.