Sha256: 2dd04c599fccb1fb35170ece127c19ef040e479d0b4ccd36262f5e224ddc143e

Contents?: true

Size: 1.64 KB

Versions: 5

Compression:

Stored size: 1.64 KB

Contents

# This code is entierly copied from VCR (http://github.com/myronmarston/vcr) by courtesy of Myron Marston  

# A Net::HTTP response that has already been read raises an IOError when #read_body
# is called with a destination string or block.
#
# This causes a problem when VCR records a response--it reads the body before yielding
# the response, and if the code that is consuming the HTTP requests uses #read_body, it
# can cause an error.
#
# This is a bit of a hack, but it allows a Net::HTTP response to be "re-read"
# after it has aleady been read.  This attemps to preserve the behavior of
# #read_body, acting just as if it had never been read.

module WebMock
  module Net
    module HTTPResponse
      def self.extended(object)
        body_object = object.instance_variable_get(:@body)
        object.instance_variable_set(:@__orig_body__,
          case body_object
            when String then body_object
            when nil then nil
            else raise ArgumentError.new("Unexpected body object: #{body_object}")
          end
        )
      end

      def read_body(dest = nil, &block)
        if @__orig_body__
          if dest && block
            raise ArgumentError.new("both arg and block given for HTTP method")
          elsif dest
            dest << @__orig_body__
          elsif block
            @body = ::Net::ReadAdapter.new(block)
            @body << @__orig_body__
            @body
          else
            @body = @__orig_body__
          end
        else
          super
        end
      ensure
        # allow subsequent calls to #read_body to proceed as normal, without our hack...
        @__orig_body__ = nil
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
webmock-1.3.5 lib/webmock/http_lib_adapters/net_http_response.rb
webmock-1.3.4 lib/webmock/http_lib_adapters/net_http_response.rb
webmock-1.3.3 lib/webmock/http_lib_adapters/net_http_response.rb
webmock-1.3.2 lib/webmock/http_lib_adapters/net_http_response.rb
webmock-1.3.1 lib/webmock/http_lib_adapters/net_http_response.rb