Mid-level Track Roadmap

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
Free preview · Lesson 1 4 min read

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 lessons
Type to start searching...