1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
require "active_support/inflector/methods"
require "active_support/dependencies"
module ActionDispatch
class MiddlewareStack < Array
class Middleware
attr_reader :args, :block
def initialize(klass_or_name, *args, &block)
@ref = ActiveSupport::Dependencies::Reference.new(klass_or_name)
@args, @block = args, block
end
def klass
@ref.get
end
def ==(middleware)
case middleware
when Middleware
klass == middleware.klass
when Class
klass == middleware
else
normalize(@ref.name) == normalize(middleware)
end
end
def inspect
klass.to_s
end
def build(app)
klass.new(app, *args, &block)
end
private
def normalize(object)
object.to_s.strip.sub(/^::/, '')
end
end
def initialize(*args)
yield(self) if block_given?
end
def insert(index, *args, &block)
index = assert_index(index, :before)
middleware = self.class::Middleware.new(*args, &block)
super(index, middleware)
end
alias_method :insert_before, :insert
def insert_after(index, *args, &block)
index = assert_index(index, :after)
insert(index + 1, *args, &block)
end
def swap(target, *args, &block)
insert_before(target, *args, &block)
delete(target)
end
def use(*args, &block)
middleware = self.class::Middleware.new(*args, &block)
push(middleware)
end
def build(app = nil, &block)
app ||= block
raise "MiddlewareStack#build requires an app" unless app
reverse.inject(app) { |a, e| e.build(a) }
end
protected
def assert_index(index, where)
i = index.is_a?(Integer) ? index : self.index(index)
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
i
end
end
end
|