Rails: custom middleware
Rack is the contract underneath every Rails app: an object responds to call(env) and returns status, headers and body. This course reads a Rails app as a stack of such objects and shows how to write your own link in it. It covers the two-method middleware shape and placing a class with use, insert_before and insert_after. It also covers wrapping versus short-circuiting a request, how gems such as OmniAuth and Rack::Attack enter the stack, and testing a middleware with a fake app.
What you'll learn
- ✓The Rack contract: call(env) returning status, headers and body
- ✓Writing a middleware with initialize(app) and call(env)
- ✓Placing middleware with use, insert_before and insert_after
- ✓Choosing between wrapping a response and short-circuiting a request
- ✓How gems add middleware, explicitly or through a Railtie
- ✓Testing middleware with a fake app and Rack::MockRequest
What Rack is
A relay race has several runners, not one. Each runs a leg and hands the baton to the next. From the stands it looks like one continuous run. Up close it's a chain of handoffs, and any runner can slow the baton down, speed it up or refuse to pass it on. A Rails request works the same way. "Rails"…
Read the full lesson free →Curriculum
7 lessonsWhat Rack is
Explains the Rack contract and shows a Rails app as an ordered stack of middleware ending in the router.
Writing a middleware: initialize and call
Builds a timing middleware with initialize and call, and shows what breaks when @app.call(env) is forgotten.
Where middleware lives: insert_before and insert_after
Covers use, insert_before, insert_after and swap, and how position decides what data a middleware can see.
Short-circuiting and wrapping the response
Compares wrapping a response with answering early, using a maintenance page and Rack::Attack throttling as examples.
Middleware from a gem: two ways in
Shows OmniAuth added through an explicit use call and Rack::Attack inserting itself through a Railtie initializer.
Testing a middleware without a real server
Tests a middleware with a fake lambda app and Rack::MockRequest, and explains why order bugs need request specs.
Putting it together: a middleware chain, built by hand
Reviews the course and sets a challenge: build a middleware chain by hand that respects order and short-circuits.