Sha256: 7c064e784d2b4959e93079e22c234c1f736571b5c01a02c5dbeb10e96f36135e

Contents?: true

Size: 1.37 KB

Versions: 7

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

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
              raise "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

7 entries across 7 versions & 1 rubygems

Version Path
acfs-2.0.0 lib/acfs/service/middleware/stack.rb
acfs-1.7.0 lib/acfs/service/middleware/stack.rb
acfs-1.6.0 lib/acfs/service/middleware/stack.rb
acfs-1.5.1 lib/acfs/service/middleware/stack.rb
acfs-1.5.0 lib/acfs/service/middleware/stack.rb
acfs-1.4.0 lib/acfs/service/middleware/stack.rb
acfs-1.3.4 lib/acfs/service/middleware/stack.rb