Sha256: aaaf07eff83554d1cf1bc60733fc460db0517ece0ab02492b031798523fe3dce

Contents?: true

Size: 751 Bytes

Versions: 3

Compression:

Stored size: 751 Bytes

Contents

module Jackhammer
  class MiddlewareCollection
    def initialize
      @entries = []
    end

    def use(klass, *args, **kwargs, &block)
      @entries << Entry.new(klass: klass, args: args, kwargs: kwargs, block: block)
    end

    def call(*args, **kwargs, &block)
      call_chain = @entries.map(&:instantiate) + [block]

      traverse = proc do |*procargs, **prockwargs|
        call_chain.shift.call(*procargs, **prockwargs, &traverse) unless call_chain.empty?
      end

      traverse.call(*args, **kwargs)
    end

    Entry = Struct.new(:klass, :args, :kwargs, :block, keyword_init: true) do
      def instantiate
        return klass unless klass.respond_to?(:new)

        klass.new(*args, **kwargs, &block)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jackhammer-1.5.1 lib/jackhammer/middleware_collection.rb
jackhammer-1.5.0 lib/jackhammer/middleware_collection.rb
jackhammer-1.5.0.rc lib/jackhammer/middleware_collection.rb