1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_dispatch/middleware/stack.rb

120 lines
2.6 KiB
Ruby
Raw Normal View History

require "active_support/inflector/methods"
module ActionDispatch
class MiddlewareStack < Array
class Middleware
def self.new(klass, *args, &block)
if klass.is_a?(self)
klass
else
super
end
end
attr_reader :args, :block
def initialize(klass, *args, &block)
@klass = klass
2008-12-15 17:33:31 -05:00
2008-12-18 13:00:54 -05:00
options = args.extract_options!
if options.has_key?(:if)
@conditional = options.delete(:if)
else
@conditional = true
end
args << options unless options.empty?
@args = args
@block = block
end
def klass
if @klass.respond_to?(:new)
@klass
elsif @klass.respond_to?(:call)
@klass.call
else
ActiveSupport::Inflector.constantize(@klass.to_s)
end
end
2008-12-18 13:00:54 -05:00
def active?
return false unless klass
2008-12-18 13:00:54 -05:00
if @conditional.respond_to?(:call)
@conditional.call
else
@conditional
end
end
def ==(middleware)
case middleware
when Middleware
klass == middleware.klass
when Class
klass == middleware
else
klass == ActiveSupport::Inflector.constantize(middleware.to_s)
end
end
def inspect
2008-12-15 17:33:31 -05:00
str = klass.to_s
args.each { |arg| str += ", #{build_args.inspect}" }
str
end
def build(app)
2008-12-15 17:33:31 -05:00
if block
klass.new(app, *build_args, &block)
2008-12-15 17:33:31 -05:00
else
klass.new(app, *build_args)
2008-12-15 17:33:31 -05:00
end
end
private
def build_args
Array(args).map { |arg| arg.respond_to?(:call) ? arg.call : arg }
end
end
2008-12-15 17:33:31 -05:00
def initialize(*args, &block)
super(*args)
block.call(self) if block_given?
end
def insert(index, *args, &block)
index = self.index(index) unless index.is_a?(Integer)
middleware = Middleware.new(*args, &block)
super(index, middleware)
end
alias_method :insert_before, :insert
def insert_after(index, *args, &block)
2009-12-28 23:18:14 -05:00
i = index.is_a?(Integer) ? index : self.index(index)
raise "No such middleware to insert after: #{index.inspect}" unless i
insert(i + 1, *args, &block)
end
def swap(target, *args, &block)
insert_before(target, *args, &block)
delete(target)
end
def use(*args, &block)
2008-12-15 17:33:31 -05:00
middleware = Middleware.new(*args, &block)
push(middleware)
end
2008-12-18 13:00:54 -05:00
def active
find_all { |middleware| middleware.active? }
end
def build(app)
2008-12-18 13:00:54 -05:00
active.reverse.inject(app) { |a, e| e.build(a) }
end
end
end