aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_controller/middleware_stack.rb
blob: b94bf6ec4ada7ab64d7be15d4ecfbad25e657b1b (plain) (blame)
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 ActionController
  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

        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.is_a?(Class)
          @klass
        else
          @klass.to_s.constantize
        end
      rescue NameError
        @klass
      end

      def active?
        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 == middleware.to_s.constantize
        end
      end

      def inspect
        str = klass.to_s
        args.each { |arg| str += ", #{arg.inspect}" }
        str
      end

      def build(app)
        if block
          klass.new(app, *args, &block)
        else
          klass.new(app, *args)
        end
      end
    end

    def initialize(*args, &block)
      super(*args)
      block.call(self) if block_given?
    end

    def insert(index, *objs)
      index = self.index(index) unless index.is_a?(Integer)
      objs = objs.map { |obj| Middleware.new(obj) }
      super(index, *objs)
    end

    alias_method :insert_before, :insert

    def insert_after(index, *objs)
      index = self.index(index) unless index.is_a?(Integer)
      insert(index + 1, *objs)
    end

    def use(*args, &block)
      middleware = Middleware.new(*args, &block)
      push(middleware)
    end

    def active
      find_all { |middleware| middleware.active? }
    end

    def build(app)
      active.reverse.inject(app) { |a, e| e.build(a) }
    end
  end
end