Class: Lepus::MiddlewareChain

Inherits:
Object
  • Object
show all
Defined in:
lib/lepus/middleware_chain.rb

Overview

Manages middleware registration and execution for producers. Middlewares can modify the message (payload, headers, routing_key, etc.) before it is published to RabbitMQ.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMiddlewareChain

Returns a new instance of MiddlewareChain.



10
11
12
# File 'lib/lepus/middleware_chain.rb', line 10

def initialize
  @middlewares = []
end

Instance Attribute Details

#middlewaresObject (readonly)

Returns the value of attribute middlewares.



8
9
10
# File 'lib/lepus/middleware_chain.rb', line 8

def middlewares
  @middlewares
end

Class Method Details

.combine(*chains) ⇒ MiddlewareChain

Creates a combined chain from multiple chains. Used to merge global and per-producer middleware chains.

Parameters:

Returns:



44
45
46
47
48
49
50
# File 'lib/lepus/middleware_chain.rb', line 44

def self.combine(*chains)
  combined = new
  chains.each do |chain|
    chain.middlewares.each { |m| combined.middlewares << m }
  end
  combined
end

Instance Method Details

#empty?Boolean

Returns true if the chain has no middlewares.

Returns:

  • (Boolean)


55
56
57
# File 'lib/lepus/middleware_chain.rb', line 55

def empty?
  @middlewares.empty?
end

#execute(message) {|message| ... } ⇒ Object

Executes the middleware chain with the given message. The final action (publishing) is called after all middlewares have processed the message.

Parameters:

Yields:

  • (message)

    Block called as the final action with the processed message.

Returns:

  • (Object)

    The result of the final action.



32
33
34
35
36
37
# File 'lib/lepus/middleware_chain.rb', line 32

def execute(message, &final_action)
  chain = @middlewares.reduce(final_action) do |next_middleware, middleware|
    ->(msg) { middleware.call(msg, next_middleware) }
  end
  chain.call(message)
end

#sizeInteger

Returns the number of middlewares in the chain.

Returns:

  • (Integer)


62
63
64
# File 'lib/lepus/middleware_chain.rb', line 62

def size
  @middlewares.size
end

#use(middleware, opts = {}) ⇒ self

Registers a middleware to the chain.

Parameters:

  • middleware (Symbol, String, Class<Lepus::Middleware>)

    The middleware to register. Can be a symbol/string (auto-loaded from producers/middlewares/) or a class.

  • opts (Hash) (defaults to: {})

    Options passed to the middleware constructor.

Returns:

  • (self)


20
21
22
23
24
# File 'lib/lepus/middleware_chain.rb', line 20

def use(middleware, opts = {})
  instance = resolve_middleware(middleware, opts)
  @middlewares << instance
  self
end