Sha256: f459afa96ba27a4a59dd5d1d8bc888bdbe4911d4f9fb32044c3bf22a608b2247

Contents?: true

Size: 1.67 KB

Versions: 191

Compression:

Stored size: 1.67 KB

Contents

module Jets::Middleware
  class Stack
    include Enumerable

    attr_accessor :middlewares
    def initialize(*args)
      @middlewares = []
      yield(self) if block_given?
    end

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

    def size
      middlewares.size
    end

    def last
      middlewares.last
    end

    def [](i)
      middlewares[i]
    end

    def unshift(klass, *args, &block)
      middlewares.unshift(build_middleware(klass, args, block))
    end

    def initialize_copy(other)
      self.middlewares = other.middlewares.dup
    end

    def insert(index, klass, *args, &block)
      index = assert_index(index, :before)
      middlewares.insert(index, build_middleware(klass, args, block))
    end

    alias_method :insert_before, :insert

    def insert_after(index, *args, &block)
      index = assert_index(index, :after)
      insert(index + 1, *args, &block)
    end

    def swap(target, *args, &block)
      index = assert_index(target, :before)
      insert(index, *args, &block)
      middlewares.delete_at(index + 1)
    end

    def delete(target)
      middlewares.delete_if { |m| m.klass == target }
    end

    def use(klass, *args, &block)
      middlewares.push(build_middleware(klass, args, block))
    end

    def build(app = Proc.new)
      middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
    end

  private

    def assert_index(index, where)
      i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index }
      raise "No such middleware to insert #{where}: #{index.inspect}" unless i
      i
    end

    def build_middleware(klass, args, block)
      Layer.new(klass, args, block)
    end
  end
end

Version data entries

191 entries across 191 versions & 4 rubygems

Version Path
jets-4.0.12 lib/jets/middleware/stack.rb
jets-4.0.11 lib/jets/middleware/stack.rb
jets-4.0.10 lib/jets/middleware/stack.rb
jets-4.0.9 lib/jets/middleware/stack.rb
jets-4.0.8 lib/jets/middleware/stack.rb
jets-4.0.7 lib/jets/middleware/stack.rb
jets-4.0.6 lib/jets/middleware/stack.rb
jets-4.0.5 lib/jets/middleware/stack.rb
jets-4.0.4 lib/jets/middleware/stack.rb
jets-4.0.3 lib/jets/middleware/stack.rb
jets-4.0.2 lib/jets/middleware/stack.rb
jets-4.0.1 lib/jets/middleware/stack.rb
jets-4.0.0 lib/jets/middleware/stack.rb
jets-3.2.2 lib/jets/middleware/stack.rb
jets-3.2.1 lib/jets/middleware/stack.rb
jets.benforeva-3.0.17.pre.mount.pre.fix lib/jets/middleware/stack.rb
jets-3.2.0 lib/jets/middleware/stack.rb
jets-3.1.5 lib/jets/middleware/stack.rb
jets-3.1.4 lib/jets/middleware/stack.rb
jets-3.1.3 lib/jets/middleware/stack.rb