Sha256: e5319c1027910b6c892b089c00169b26dd66526798aa5b407481e57ea1b06014

Contents?: true

Size: 1.08 KB

Versions: 1

Compression:

Stored size: 1.08 KB

Contents

module Walle
  module Middlewares
    class Builder
      class Proxy
        attr_reader :target_class, :app, :args, :block

        def initialize(target_class, app, *args, &block)
          @target_class, @app, @args, @block = target_class, app, args, block
        end

        def call(env)
          with_env(env) do |target|
            target.before if target.respond_to?(:before)
            app.call(env)
            target.after if target.respond_to?(:after)
          end
        end

        private

        def with_env(env)
          yield target_class.new(env, *args, &block)
        end
      end

      def initialize(default_app = nil, &block)
        @use, @run = [], default_app
        instance_eval(&block) if block_given?
      end

      def use(middleware, *args, &block)
        @use << ->(app){ Proxy.new(middleware, app, *args, &block) }
      end

      def to_app(app)
        app ||= @run
        fail 'missing run statement' unless app
        @use.reverse.inject(app){|a, e| e[a] }
      end

      def call(env)
        to_app.call(env)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
walle-0.1.0 lib/walle/middlewares/builder.rb