ruby
42 lines · 8 steps
Building a middleware pipeline in Ruby
Compose a chain of block-based middlewares into a single callable that wraps each layer around the next.
Explained by
highlit
1class Pipeline
2 def initialize
3 @middlewares = []
4 end
5
6 def use(&middleware)
7 @middlewares << middleware
8 self
9 end
10
11 def call(request)
12 stack = @middlewares.reverse.reduce(->(req) { req }) do |next_step, middleware|
13 ->(req) { middleware.call(req, next_step) }
14 end
15 stack.call(request)
16 end
17end
18
19pipeline = Pipeline.new
20
21pipeline.use do |request, nxt|
22 started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
23 response = nxt.call(request)
24 elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
25 response.merge(duration_ms: (elapsed * 1000).round(2))
26end
27
28pipeline.use do |request, nxt|
29 token = request.dig(:headers, "Authorization")
30 next { status: 401, body: "Unauthorized" } unless token == "Bearer secret"
31
32 nxt.call(request.merge(current_user: "alice"))
33end
34
35pipeline.use do |request, nxt|
36 Rails.logger.info("#{request[:method]} #{request[:path]} user=#{request[:current_user]}")
37 nxt.call(request)
38end
39
40pipeline.use do |request, _nxt|
41 { status: 200, body: "Hello, #{request[:current_user]}" }
42end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Folding functions with reduce turns a list of layers into one nested callable, each holding a reference to the next.
- 2Passing a next_step callback lets each middleware decide whether to continue, short-circuit, or transform the request.
- 3Returning self from configuration methods enables fluent chaining and a clean setup API.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-middleware-pipeline-in-ruby-explained-ruby-8359/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.