Class: WebMock::RackResponse

Inherits:
Response show all
Defined in:
lib/webmock/rack_response.rb

Instance Method Summary collapse

Methods inherited from Response

#==, #body, #body=, #exception, #exception=, #headers, #headers=, #options=, #raise_error_if_any, #should_timeout, #status, #status=

Constructor Details

#initialize(app) ⇒ RackResponse

Returns a new instance of RackResponse.



5
6
7
# File 'lib/webmock/rack_response.rb', line 5

def initialize(app)
  @app = app
end

Instance Method Details

#body_from_rack_response(response) ⇒ Object



21
22
23
24
25
26
# File 'lib/webmock/rack_response.rb', line 21

def body_from_rack_response(response)
  body = "".dup
  response.each { |line| body << line }
  response.close if response.respond_to?(:close)
  return body
end

#build_rack_env(request) ⇒ Object



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
# File 'lib/webmock/rack_response.rb', line 28

def build_rack_env(request)
  uri = request.uri
  headers = (request.headers || {}).dup
  body = request.body || ''

  env = {
    # CGI variables specified by Rack
    'REQUEST_METHOD' => request.method.to_s.upcase,
    'CONTENT_TYPE'   => headers.delete('Content-Type'),
    'CONTENT_LENGTH' => body.bytesize,
    'PATH_INFO'      => uri.path,
    'QUERY_STRING'   => uri.query || '',
    'SERVER_NAME'    => uri.host,
    'SERVER_PORT'    => uri.port,
    'SCRIPT_NAME'    => ""
  }

  env['HTTP_AUTHORIZATION'] = 'Basic ' + [uri.userinfo].pack('m').delete("\r\n") if uri.userinfo

  # Rack-specific variables
  env['rack.input']      = StringIO.new(body)
  env['rack.errors']     = $stderr
  if !Rack.const_defined?(:RELEASE) || Rack::RELEASE < "3"
    env['rack.version']    = Rack::VERSION
  end
  env['rack.url_scheme'] = uri.scheme
  env['rack.run_once']   = true
  env['rack.session']    = session
  env['rack.session.options'] = session_options

  headers.each do |k, v|
    env["HTTP_#{k.tr('-','_').upcase}"] = v
  end

  env
end

#evaluate(request) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/webmock/rack_response.rb', line 9

def evaluate(request)
  env = build_rack_env(request)

  status, headers, response = @app.call(env)

  Response.new(
    body: body_from_rack_response(response),
    headers: headers,
    status: [status, Rack::Utils::HTTP_STATUS_CODES[status]]
  )
end

#sessionObject



65
66
67
# File 'lib/webmock/rack_response.rb', line 65

def session
  @session ||= {}
end

#session_optionsObject



69
70
71
# File 'lib/webmock/rack_response.rb', line 69

def session_options
  @session_options ||= {}
end