Class: Funktor::MiddlewareChain

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

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMiddlewareChain

Returns a new instance of MiddlewareChain.



5
6
7
# File 'lib/funktor/middleware_chain.rb', line 5

def initialize
  @entries = []
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



3
4
5
# File 'lib/funktor/middleware_chain.rb', line 3

def entries
  @entries
end

Instance Method Details

#add(klass, *args) ⇒ Object



13
14
15
16
# File 'lib/funktor/middleware_chain.rb', line 13

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

#insert_after(oldklass, newklass, *args) ⇒ Object



29
30
31
32
33
# File 'lib/funktor/middleware_chain.rb', line 29

def insert_after(oldklass, newklass, *args)
  remove(newklass)
  i = entries.index { |entry| entry.klass == oldklass } || entries.count - 1
  entries.insert(i + 1, Entry.new(newklass, *args))
end

#insert_before(oldklass, newklass, *args) ⇒ Object



23
24
25
26
27
# File 'lib/funktor/middleware_chain.rb', line 23

def insert_before(oldklass, newklass, *args)
  remove(newklass)
  i = entries.index { |entry| entry.klass == oldklass } || 0
  entries.insert(i, Entry.new(newklass, *args))
end

#invoke(*args) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/funktor/middleware_chain.rb', line 35

def invoke(*args)
  return yield if @entries.empty?

  middlewares = entries.map(&:instantiate)
  traverse_chain = proc do
    if middlewares.empty?
      yield
    else
      middlewares.shift.call(*args, &traverse_chain)
    end
  end
  traverse_chain.call
end

#prepend(klass, *args) ⇒ Object



18
19
20
21
# File 'lib/funktor/middleware_chain.rb', line 18

def prepend(klass, *args)
  remove(klass)
  entries.insert(0, Entry.new(klass, *args))
end

#remove(klass) ⇒ Object



9
10
11
# File 'lib/funktor/middleware_chain.rb', line 9

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