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({}).inspectThe 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
- Sinatra Basics
- Routes and Params
- JSON APIs
- Middleware and Rack