Rack – the contract under every Ruby web app
Puma, Falcon or WEBrick on one side, Sinatra, Roda, Hanami or Rails on the other – and any of them fits any other. That works because they all keep one small contract: Rack (Christian Neukirchen, 2007, after Python's WSGI). A web app is any object that answers call(env). env is a Hash describing the request; the answer is an Array of three things: the status (200, 404, …), the headers (a Hash) and the body – something with each that yields strings, usually an Array.
The smallest object with a call method is a lambda. So this is a complete web app:
install_gem "rack"
require "rack"
# A Rack app: anything that answers call(env)
hello = ->(env) do
[200,
{ "content-type" => "text/html" },
["<h1>Hello from Rack!</h1><p>No framework - just a lambda.</p>"]]
end
# Call it yourself: an env goes in, a triple comes out
p hello.call({ "REQUEST_METHOD" => "GET", "PATH_INFO" => "/" })
show_browser hello, "/"The printed triple is the whole answer; the mini browser turns it into a page. Rack 3 wants header names in lower case (content-type), as HTTP/2 does.
The env, Rack::Request and Rack::Response
A server reads the HTTP request off the network and turns it into the env Hash: REQUEST_METHOD (GET, POST …), PATH_INFO (the path), QUERY_STRING (what follows the ?), one HTTP_… key per request header, and rack.input for the contents of a form. Rack::MockRequest.env_for builds such a Hash without any server – handy for trying things out and for tests.
Picking strings out of a Hash soon gets tedious. Rack::Request wraps the env (path_info, get?, params with the query string already decoded), and Rack::Response collects status, headers and body and hands back the triple with finish. With a case on the path you already have a router:
# What a server hands the app for http://localhost/hello?name=Ada
env = Rack::MockRequest.env_for("/hello?name=Ada")
env.slice("REQUEST_METHOD", "PATH_INFO", "QUERY_STRING").each do |key, value|
puts "#{key} = #{value.inspect}"
end
# Rack::Request reads the env, Rack::Response builds the triple
greeter = ->(env) do
req = Rack::Request.new(env)
res = Rack::Response.new
res["content-type"] = "text/html"
case req.path_info
when "/"
res.write "<h1>Greeter</h1><a href='/hello?name=Ada'>Greet Ada</a>"
when "/hello"
who = Rack::Utils.escape_html(req.params.fetch("name", "stranger"))
res.write "<p>Hello, #{who}!</p><a href='/'>Back</a>"
else
res.status = 404
res.write "<p>Nothing here.</p><a href='/'>Back</a>"
end
res.finish
end
p greeter.call(env)
show_browser greeter, "/hello?name=Ada"Try /hello?name=Chunky and /pizza in the address bar. Rack::Utils.escape_html makes sure a name like <script> arrives as text, not as code.
Middleware: an app around an app
Because every app has the same shape, you can put one around another. A middleware gets the inner app in initialize, and its own call passes the env on, waits for the triple and may change it on the way back – or answer by itself without asking the inner app at all. That's how logging, sessions, compression or protection against attacks get into any Rack app, whatever framework it is written in. Two small ones:
# Middleware: measures how long the inner app takes
class Stopwatch
def initialize(app)
@app = app
end
def call(env)
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
status, headers, body = @app.call(env)
took = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
headers["x-runtime"] = format("%.6f", took)
[status, headers, body]
end
end
# Middleware: writes every request to the log
class RequestLog
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
puts "#{env["REQUEST_METHOD"]} #{env["PATH_INFO"]} -> #{status}"
[status, headers, body]
end
end
# An onion: RequestLog outside, Stopwatch inside, greeter at the core
app = RequestLog.new(Stopwatch.new(greeter))
response = Rack::MockRequest.new(app).get("/hello?name=Ada")
puts response.status, response.headers["x-runtime"], response.body
response = Rack::MockRequest.new(app).get("/pizza")
puts response.statusThe request goes in through the layers like through an onion, and the answer comes back out the same way: RequestLog sees the status only once Stopwatch and greeter are done. Rack::MockRequest calls the app the way a server would and wraps the answer in an object with status, headers and body.
Rack::Builder: use, run, map
Nested new calls soon get hard to read. Rack::Builder says the same with three words: use adds a middleware (the first one is the outermost), run names the app at the core, and map mounts another app under a path prefix:
# Rack::Builder: the same onion, written as a list
site = Rack::Builder.app do
use RequestLog
use Stopwatch
map "/shop" do
run ->(env) {
where = "SCRIPT_NAME = #{env["SCRIPT_NAME"]}, PATH_INFO = #{env["PATH_INFO"]}"
[200, { "content-type" => "text/html" }, ["<p>#{where}</p><a href='/'>Back</a>"]]
}
end
run greeter
end
puts Rack::MockRequest.new(site).get("/shop/bacon").body
show_browser site, "/shop/bacon"Under map "/shop" the inner app sees only the rest of the path: the prefix moves from PATH_INFO to SCRIPT_NAME, so a mounted app need not know where it is mounted. The lines RequestLog prints appear under the page in the mini browser.
Sinatra, Roda and Rails are Rack apps
The frameworks of the next lessons are exactly this, with a lot of comfort on top. In Rails (lesson 56) the app is Rails.application, and its call(env) sits behind a stack of some 25 middlewares (bin/rails middleware lists them). A Sinatra app (lesson 54) is a class with a class method call(env), and so is a Roda app (lesson 55). Each of them can stand after run, hang under map or sit behind your own use. And the mini browser? It is a tiny Rack server: it builds an env from the address bar, calls call and draws the body.
config.ru – the inside of a Rack::Builder block:# config.ru
require "rack"
use Rack::Runtime
run ->(env) { [200, { "content-type" => "text/plain" }, ["Hello from config.ru!"]] }After gem install rackup puma, rackup in that folder serves it at localhost:9292. puma alone reads config.ru too – as does every Rack server: one file for all of them.Megaphone: it should turn every piece of the inner app's body into capital letters (upcase) and add the header x-megaphone with the value on; the status and the other headers stay as they are. The mini browser below shows the quiet app through the megaphone.install_gem "rack"
require "rack"
class Megaphone
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
# upper-case every piece of the body, and add the header x-megaphone: on
[status, headers, body]
end
end
quiet = ->(env) { [200, { "content-type" => "text/html" }, ["<h1>Hello, Rack!</h1>"]] }
show_browser Megaphone.new(quiet), "/"