Sha256: 9cccd0c74151fc12d32b51a4566800ab70ac60ac4d8559959bc3db28e62a3bc8

Contents?: true

Size: 1.38 KB

Versions: 70

Compression:

Stored size: 1.38 KB

Contents

=begin

Conditionally use Rack Middleware.

Usage:

condition_proc = ->(env) { env['PATH_INFO'] == '/match' }
use_when condition_proc, SomeMiddleware, options

I feel sure there must be something like this officially supported somewhere, but I can't find it.

=end

module Rack
  module PactBroker
    module UseWhen
      class ConditionallyUseMiddleware
        def initialize(app, condition_proc, middleware, *args, &block)
          @app_without_middleware = app
          @condition_proc = condition_proc
          @middleware = middleware
          @args = args
          @block = block
        end

        def call(env)
          if condition_proc.call(env)
            app_with_middleware.call(env)
          else
            app_without_middleware.call(env)
          end
        end

        private

        attr_reader :app_without_middleware, :condition_proc, :middleware, :args, :block

        def app_with_middleware
          @app_with_middleware ||= begin
            rack_builder = ::Rack::Builder.new
            rack_builder.use middleware, *args, &block
            rack_builder.run app_without_middleware
            rack_builder.to_app
          end
        end
      end

      refine Rack::Builder do
        def use_when(condition_proc, middleware, *args, &block)
          use(ConditionallyUseMiddleware, condition_proc, middleware, *args, &block)
        end
      end
    end
  end
end

Version data entries

70 entries across 70 versions & 1 rubygems

Version Path
pact_broker-2.106.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.105.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.104.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.103.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.102.2 lib/rack/pact_broker/use_when.rb
pact_broker-2.102.1 lib/rack/pact_broker/use_when.rb
pact_broker-2.102.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.101.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.100.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.99.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.98.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.97.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.96.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.95.1 lib/rack/pact_broker/use_when.rb
pact_broker-2.95.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.94.0 lib/rack/pact_broker/use_when.rb
pact_broker-2.93.4 lib/rack/pact_broker/use_when.rb
pact_broker-2.93.3 lib/rack/pact_broker/use_when.rb
pact_broker-2.93.2 lib/rack/pact_broker/use_when.rb
pact_broker-2.93.1 lib/rack/pact_broker/use_when.rb