0Pricing
Ruby Academy · Lesson

Middleware and Rack

The Rack stack.

What Is Rack?

Rack is the minimal interface between Ruby web servers and frameworks. Sinatra, Rails, and others all run on Rack.

  • Standardizes how requests and responses flow
  • Enables reusable middleware
  • A Rack app is anything that responds to call(env)
app = lambda do |env|
  [200, { 'Content-Type' => 'text/plain' }, ['Hello Rack']]
end

puts app.call({}).inspect

The Rack Contract

A Rack app's call must return a three element array:

  • Status integer (e.g. 200)
  • Headers hash
  • Body that responds to each (usually an array of strings)
status, headers, body = 200, { 'Content-Type' => 'text/html' }, ['<h1>Hi</h1>']
puts status
puts headers.inspect
body.each { |chunk| puts chunk }

All lessons in this course

  1. Sinatra Basics
  2. Routes and Params
  3. JSON APIs
  4. Middleware and Rack
← Back to Ruby Academy