Class: Toro::Middleware::Chain

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/toro/middleware/chain.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Chain

Returns a new instance of Chain.

Yields:

  • (_self)

Yield Parameters:


15
16
17
18
# File 'lib/toro/middleware/chain.rb', line 15

def initialize
  @entries = []
  yield self if block_given?
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries


5
6
7
# File 'lib/toro/middleware/chain.rb', line 5

def entries
  @entries
end

Instance Method Details

#add(klass, *args) ⇒ Object


24
25
26
27
# File 'lib/toro/middleware/chain.rb', line 24

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

#clearObject


51
52
53
# File 'lib/toro/middleware/chain.rb', line 51

def clear
  entries.clear
end

#each(&block) ⇒ Object


11
12
13
# File 'lib/toro/middleware/chain.rb', line 11

def each(&block)
  entries.each(&block)
end

#exists?(klass) ⇒ Boolean

Returns:

  • (Boolean)

43
44
45
# File 'lib/toro/middleware/chain.rb', line 43

def exists?(klass)
  any? { |entry| entry.klass == klass }
end

#initialize_copy(copy) ⇒ Object


7
8
9
# File 'lib/toro/middleware/chain.rb', line 7

def initialize_copy(copy)
  copy.instance_variable_set(:@entries, entries.dup)
end

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


36
37
38
39
40
41
# File 'lib/toro/middleware/chain.rb', line 36

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

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


29
30
31
32
33
34
# File 'lib/toro/middleware/chain.rb', line 29

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

#invoke(*args, &final_action) ⇒ Object


55
56
57
58
59
60
61
62
63
64
65
# File 'lib/toro/middleware/chain.rb', line 55

def invoke(*args, &final_action)
  chain = retrieve.dup
  traverse_chain = lambda do
    if chain.empty?
      final_action.call
    else
      chain.shift.call(*args, &traverse_chain)
    end
  end
  traverse_chain.call
end

#remove(klass) ⇒ Object


20
21
22
# File 'lib/toro/middleware/chain.rb', line 20

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

#retrieveObject


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

def retrieve
  map(&:make_new)
end