/
middleware.rb
104 lines (94 loc) · 2.51 KB
/
middleware.rb
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
module Lotus
# Rack middleware stack for an application
#
# @since 0.1.0
# @api private
class Middleware
# Instantiate a middleware stack
#
# @param configuration [Lotus::Configuration] the application's configuration
#
# @return [Lotus::Middleware] the new stack
#
# @since 0.1.0
# @api private
#
# @see Lotus::Configuration
def initialize(configuration)
@stack = []
@configuration = configuration
end
# Load the middleware stack
#
# @param application [Lotus::Application] the application loading the middleware
#
# @return [Lotus::Middleware] the loaded middleware stack
#
# @since x.x.x
# @api private
#
# @see http://rdoc.info/gems/rack/Rack/Builder
def load!(application, namespace)
@namespace = namespace
@builder = ::Rack::Builder.new
load_default_stack(application)
@stack.each { |m, args, block| @builder.use load_middleware(m), *args, &block }
@builder.run application.routes
self
end
# Process a request.
# This method makes the middleware stack compatible with the Rack protocol.
#
# @param env [Hash] a Rack env
#
# @return [Array] a serialized Rack response
#
# @since 0.1.0
# @api private
def call(env)
@builder.call(env)
end
# Add a middleware to the stack.
#
# @param middleware [Object] a Rack middleware
# @param *args [Array] optional arguments to pass to the Rack middleware
# @param &blk [Proc] an optional block to pass to the Rack middleware
#
# @return [Array] the middleware that was added
#
# @since x.x.x
def use(middleware, *args, &blk)
@stack << [middleware, args, blk]
end
# @api private
# @since x.x.x
def load_middleware(middleware)
case middleware
when String
@namespace.const_get(middleware)
else
middleware
end
end
# @api private
# @since x.x.x
def load_default_stack(application)
@default_stack_loaded ||= begin
if @configuration.sessions.enabled?
use(*@configuration.sessions.middleware)
end
if @configuration.serve_assets
@configuration.assets.entries.each do |path, children|
use Rack::Static, urls: children, root: path
end
end
use Rack::MethodOverride
unless application.routes.defined?
require 'lotus/welcome'
use Lotus::Welcome
end
true
end
end
end
end