Class: Zizq::Middleware::Chain

Inherits:
Object
  • Object
show all
Defined in:
lib/zizq/middleware.rb,
sig/generated/zizq/middleware.rbs

Overview

A linked chain of middleware ending with a terminal.

Each middleware must implement #call(arg, chain) where chain is the next link. The terminal implements #call(arg).

When no middleware is registered, #call delegates directly to the terminal with zero overhead.

chain = Zizq::Middleware::Chain.new(dispatcher)
chain.use(LoggingMiddleware.new)
chain.use(MetricsMiddleware.new)
chain.call(job)
# MetricsMiddleware -> LoggingMiddleware -> dispatcher

RBS:

  • generic Arg -- the type flowing through the chain

  • generic Ret -- the return type of the terminal

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(terminal) ⇒ Chain

Returns a new instance of Chain.

Signature:

  • (untyped) -> void

Parameters:

  • terminal (Object)


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

def initialize(terminal) #: (untyped) -> void
  @terminal = terminal
  @entries = [] #: Array[untyped]
  @built = nil #: untyped?
end

Instance Attribute Details

#terminalObject

The terminal callable at the end of the chain.

Returns:

  • (Object)


27
28
29
# File 'lib/zizq/middleware.rb', line 27

def terminal
  @terminal
end

Instance Method Details

#buildObject

Signature:

  • () -> untyped

Returns:

  • (Object)


54
55
56
57
58
59
60
61
62
63
# File 'lib/zizq/middleware.rb', line 54

def build #: () -> untyped
  @built ||=
    if @entries.empty?
      @terminal
    else
      @entries
        .reverse
        .reduce(@terminal) { |next_link, mw| Link.new(mw, next_link) }
    end
end

#call(arg) ⇒ Object

Execute the chain with the given argument.

Parameters:

  • arg (Object)

Returns:

  • (Object)


48
49
50
# File 'lib/zizq/middleware.rb', line 48

def call(arg) #: (Arg) -> Ret
  build.call(arg)
end

#use(middleware) ⇒ Object

Append a middleware to the chain.

Parameters:

  • middleware (Object)

Returns:

  • (Object)


42
43
44
45
# File 'lib/zizq/middleware.rb', line 42

def use(middleware) #: (untyped) -> void
  @entries << middleware
  @built = nil
end