Skip to content

Instantly share code, notes, and snippets.

Created May 19, 2012 17:17
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Brief Introduction to Rack -- from codereading activity

Brief Introduction to Rack




for communication between Server and Ruby WAF


implementing the SPEC and thin, useful helpers. Base of Sinatra, Rails, etc.

Rack Specificatoin


A Rack application is an object that responds to call(env).

and returns an Array of exactly three values: status, headers, and body.


Server should provide env. Apps can read / overwrite it.


Apps should respond status, headers, and the body. Server sends them to a client.

Rack Application


App should respond to call. Env is supplied as an argument. This should an array like the following.

 {'Content-Type' => 'text/plain'},

The Simplest Application

Proc object responds to call. So, this is the simplest. run is a helper method (cover it later). run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }

Rack Middleware


middleware is just an idiom.

The common middleware takes an app as an argument of initializer.

An instance of the middleware responds to call, and in that, the original app will be called with before and after process.

combine, like a Rack

The concept of Rack Middleware is similar to a linked list. Multiple middlewares can be recursively connected, because a middleware is basically an app.

This is essence of rack. This provides great extensibility.

[fig here]

How rack works? - On startup

Start point

Take as an example.

require 'rack/lobster'

use Rack::ShowExceptions

You can run this with rackup command.

  • rackup ->
  • Rack::Server.start : parse options ->
  • Rack::Builder : parse .ru file, create app ->
  • Rack::Server#start : set server / running options, start server ->
  • : kick WEBrick as server

How rack works? - On request

  • Rack::Handler::WEBrick#service : generate env, ->
  • your app : get information from env, create the response ->
  • Rack::Handler::WEBrick#service : process app response and return to the client
Copy link

TODO: add images for Rack::Builder. The mechanism is a little bit complex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment