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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 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.