Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 80 lines (65 sloc) 2.445 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
require 'faraday'

module VCR
  module Middleware
    class Faraday < ::Faraday::Middleware
      include Common

      class HttpConnectionNotAllowedError < StandardError; end

      def call(env)
        VCR::HttpStubbingAdapters::Faraday.exclusively_enabled do
          VCR.use_cassette(*cassette_arguments(env)) do |cassette|
            request = request_for(env)
            request_matcher = request.matcher(cassette.match_requests_on)

            if VCR::HttpStubbingAdapters::Faraday.uri_should_be_ignored?(request.uri)
              @app.call(env)
            elsif response = VCR::HttpStubbingAdapters::Faraday.stubbed_response_for(request_matcher)
              env.update(
                :status => response.status.code,
                :response_headers => correctly_cased_headers(response.headers || {}),
                :body => response.body
              )

              env[:response].finish(env)
            elsif VCR::HttpStubbingAdapters::Faraday.http_connections_allowed?
              response = @app.call(env)

              # Checking #enabled? isn't strictly needed, but conforms
              # the Faraday adapter to the behavior of the other adapters
              if VCR::HttpStubbingAdapters::Faraday.enabled?
                VCR.record_http_interaction(VCR::HTTPInteraction.new(request, response_for(env)))
              end

              response
            else
              raise HttpConnectionNotAllowedError.new(
                "Real HTTP connections are disabled. Request: #{request.method.inspect} #{request.uri}"
              )
            end
          end
        end
      end

      private

        def request_for(env)
          VCR::Request.new(
            env[:method],
            env[:url].to_s,
            env[:body],
            env[:request_headers]
          )
        end

        def response_for(env)
          response = env[:response]

          VCR::Response.new(
            VCR::ResponseStatus.new(response.status, nil),
            response.headers,
            response.body,
            '1.1'
          )
        end

        def correctly_cased_headers(headers)
          correctly_cased_hash = {}

          headers.each do |key, value|
            key = key.to_s.split('-').map { |segment| segment.capitalize }.join("-")
            correctly_cased_hash[key] = value
          end

          correctly_cased_hash
        end
    end
  end
end
Something went wrong with that request. Please try again.