class VCR::Middleware::Rack

Rack middleware that uses a VCR cassette for each incoming HTTP request.

@example

app = Rack::Builder.new do
  use VCR::Middleware::Rack do |cassette, env|
    cassette.name "rack/#{env['SERVER_NAME']}"
    cassette.options :record => :new_episodes
  end

  run MyRackApp
end

@note This will record/replay outbound HTTP requests made by your rack app.

Public Class Methods

new(app, &block) click to toggle source

Constructs a new instance of VCR's rack middleware.

@param [#call] app the rack app @yield the cassette configuration block @yieldparam [CassetteArguments] cassette the cassette configuration object @yieldparam [(optional) Hash] env the rack env hash @raise [ArgumentError] if no configuration block is provided

# File lib/vcr/middleware/rack.rb, line 53
def initialize(app, &block)
  raise ArgumentError.new("You must provide a block to set the cassette options") unless block
  @app, @cassette_arguments_block, @mutex = app, block, Mutex.new
end

Public Instance Methods

call(env) click to toggle source

Implements the rack middleware interface.

@param [Hash] env the rack env hash @return [Array(Integer, Hash, each)] the rack response

# File lib/vcr/middleware/rack.rb, line 62
def call(env)
  @mutex.synchronize do
    VCR.use_cassette(*cassette_arguments(env)) do
      @app.call(env)
    end
  end
end

Private Instance Methods

cassette_arguments(env) click to toggle source
# File lib/vcr/middleware/rack.rb, line 72
def cassette_arguments(env)
  arguments = CassetteArguments.new
  call_block(@cassette_arguments_block, arguments, env)
  [arguments.name, arguments.options]
end