Create a gist now

Instantly share code, notes, and snippets.

Brief Introduction to Rack -- from codereading activity

Brief Introduction to Rack

@tomy_kaira

Rack

Specification

for communication between Server and Ruby WAF

Library

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

Rack Specificatoin

http://rack.rubyforge.org/doc/SPEC.html

Basic

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

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

Environment

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

Response

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

Rack Application

call(env)

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

[200, 
 {'Content-Type' => 'text/plain'},
 ['OK']]

The Simplest Application

Proc object responds to call. So, this is the simplest. run is a helper method (cover it later).

config.ru run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }

Rack Middleware

wrap

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]

http://www.charlestonforge.com/Images/bakersracksandetageres/images/6265-15-S-O-HP.jpg

How rack works? - On startup

Start point

Take lobster.ru as an example.

require 'rack/lobster'

use Rack::ShowExceptions
run Rack::Lobster.new

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 ->
  • Rack::Handler::WEBrick.run : kick WEBrick as server

How rack works? - On request

  • Rack::Handler::WEBrick#service : generate env, app.call ->
  • your app : get information from env, create the response ->
  • Rack::Handler::WEBrick#service : process app response and return to the client
@tomykaira
Owner

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