Class: Stipa::MiddlewareStack

Inherits:
Object
  • Object
show all
Defined in:
lib/stipa/middleware.rb

Overview

A minimal middleware stack inspired by Rack.

Middleware signature: call(req, res) -> res

The stack is compiled ONCE at server start into a chain of nested closures. Per-request cost is zero stack traversal — it’s just nested method calls. The first ‘use`-d middleware is outermost (runs first on the way in, last on the way out).

Example:

app.use Stipa::Middleware::RequestId
app.use Stipa::Middleware::Timing
app.use Stipa::Middleware::Cors, origins: ['https://example.com']

Instance Method Summary collapse

Constructor Details

#initializeMiddlewareStack

Returns a new instance of MiddlewareStack.



18
19
20
# File 'lib/stipa/middleware.rb', line 18

def initialize
  @layers = []
end

Instance Method Details

#build(app) ⇒ Object

Compile the stack around ‘app` (the router callable). Returns a single callable: call(req, res) -> res



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/stipa/middleware.rb', line 36

def build(app)
  # Reverse so first-added middleware ends up outermost
  @layers.reverse_each do |klass_or_proc, opts|
    inner = app
    app = if klass_or_proc.respond_to?(:new)
            klass_or_proc.new(inner, **opts)
          else
            # Plain lambda/proc: wrap so it receives next_app context
            ->(req, res) { klass_or_proc.call(req, res, inner) }
          end
  end
  app
end

#empty?Boolean

Returns:

  • (Boolean)


50
# File 'lib/stipa/middleware.rb', line 50

def empty?; @layers.empty?; end

#prepend(middleware, **options) ⇒ Object

Insert a middleware at the front of the stack (runs before all others). Used internally by App to prepend Static before user middleware.



29
30
31
32
# File 'lib/stipa/middleware.rb', line 29

def prepend(middleware, **options)
  @layers.unshift([middleware, options])
  self
end

#use(middleware, **options) ⇒ Object



22
23
24
25
# File 'lib/stipa/middleware.rb', line 22

def use(middleware, **options)
  @layers << [middleware, options]
  self
end