Class: EXEL::Middleware::Chain

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

Overview

Chain of middleware to be invoked in sequence around each processor execution.

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeChain

Returns a new instance of Chain.



30
31
32
# File 'lib/exel/middleware/chain.rb', line 30

def initialize
  @entries = []
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



26
27
28
# File 'lib/exel/middleware/chain.rb', line 26

def entries
  @entries
end

Instance Method Details

#add(klass, *args) ⇒ Object

Adds a middleware class to the chain. If it is already in the chain it will be removed and added to the end. Any additional arguments will be passed to new when the middleware is created.



36
37
38
39
# File 'lib/exel/middleware/chain.rb', line 36

def add(klass, *args)
  remove(klass)
  @entries << Entry.new(klass, args)
end

#include?(klass) ⇒ Boolean

Returns true if the given class is in the chain.

Returns:

  • (Boolean)


47
48
49
# File 'lib/exel/middleware/chain.rb', line 47

def include?(klass)
  @entries.any? { |entry| entry.klass == klass }
end

#invoke(*args) ⇒ Object

Calls each middleware in the chain.



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/exel/middleware/chain.rb', line 52

def invoke(*args)
  chain = @entries.map { |entry| entry.klass.new(*entry.args) }

  traverse_chain = lambda do
    if chain.empty?
      yield
    else
      chain.shift.call(*args, &traverse_chain)
    end
  end

  traverse_chain.call
end

#remove(klass) ⇒ Object

Removes a middleware class from the chain.



42
43
44
# File 'lib/exel/middleware/chain.rb', line 42

def remove(klass)
  @entries.delete_if { |entry| entry.klass == klass }
end