Sha256: 991ae7d2b21d997d9fe2d0896aaa03b612a01b1b35a0bf6cfc5ef9d5e0a2a2b6

Contents?: true

Size: 1.34 KB

Versions: 14

Compression:

Stored size: 1.34 KB

Contents

module Acfs
  class Service
    module Middleware
      class Stack
        include Enumerable

        MUTEX = Mutex.new
        IDENTITY = -> (i) { i }

        attr_reader :middlewares

        def initialize
          @middlewares = []
        end

        def call(request)
          build! unless @app

          @app.call request
        end

        def build!
          return if @app

          MUTEX.synchronize do
            return if @app

            @app = build
          end
        end

        def build(app = IDENTITY)
          middlewares.reverse.inject(app) do |next_middleware, current_middleware|
            klass, args, block = current_middleware
            args ||= []

            if klass.is_a?(Class)
              klass.new(next_middleware, *args, &block)
            elsif klass.respond_to?(:call)
              lambda do |env|
                next_middleware.call(klass.call(env, *args))
              end
            else
              fail "Invalid middleware, doesn't respond to `call`: #{klass.inspect}"
            end
          end
        end

        def insert(index, klass, *args, &block)
          middlewares.insert(index, [klass, args, block])
        end

        def each
          middlewares.each { |x| yield x.first }
        end

        def clear
          middlewares.clear
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
acfs-1.3.2 lib/acfs/service/middleware/stack.rb
acfs-1.3.1 lib/acfs/service/middleware/stack.rb
acfs-1.3.0 lib/acfs/service/middleware/stack.rb
acfs-1.2.1 lib/acfs/service/middleware/stack.rb
acfs-0.50.0 lib/acfs/service/middleware/stack.rb
acfs-1.2.0 lib/acfs/service/middleware/stack.rb
acfs-0.49.1 lib/acfs/service/middleware/stack.rb
acfs-1.1.1 lib/acfs/service/middleware/stack.rb
acfs-0.49.0 lib/acfs/service/middleware/stack.rb
acfs-1.1.0 lib/acfs/service/middleware/stack.rb
acfs-0.48.2 lib/acfs/service/middleware/stack.rb
acfs-1.0.1 lib/acfs/service/middleware/stack.rb
acfs-0.48.1 lib/acfs/service/middleware/stack.rb
acfs-1.0.0 lib/acfs/service/middleware/stack.rb