Class: HTTPAdapter::RackRequestAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/httpadapter/adapters/rack.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, error_stream = STDERR) ⇒ RackRequestAdapter

Returns a new instance of RackRequestAdapter.



23
24
25
26
27
28
29
# File 'lib/httpadapter/adapters/rack.rb', line 23

def initialize(request, error_stream=STDERR)
  unless request.kind_of?(Rack::Request)
    raise TypeError, "Expected Rack::Request, got #{request.class}."
  end
  @request = request
  @error_stream = error_stream
end

Class Method Details

.from_ary(array) ⇒ Object



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
80
81
82
83
84
85
86
87
88
89
# File 'lib/httpadapter/adapters/rack.rb', line 46

def self.from_ary(array)
  # These contortions are really obnoxious; lossiness is bad!
  method, uri, headers, body = array
  env = {}
  method = method.to_s.upcase
  uri = Addressable::URI.parse(uri)
  body_io = StringIO.new
  body.each do |chunk|
    unless chunk.kind_of?(String)
      raise TypeError, "Expected String, got #{chunk.class}."
    end
    body_io.write(chunk)
  end
  body_io.rewind

  # PEP333 variables
  env['REQUEST_METHOD'] = method
  env['SERVER_NAME'] = uri.host || ''
  env['SERVER_PORT'] = uri.port || '80'
  env['SCRIPT_NAME'] = ''
  env['PATH_INFO'] = uri.path
  env['QUERY_STRING'] = uri.query || ''

  # Rack-specific variables
  env['rack.version'] = Rack::VERSION
  env['rack.input'] = body_io
  env['rack.errors'] = @error_stream
  env['rack.multithread'] = true # maybe?
  env['rack.multiprocess'] = true # maybe?
  env['rack.run_once'] = false
  env['rack.url_scheme'] = uri.scheme || 'http'

  headers.each do |header, value|
    case header.downcase
    when 'content-length'
      env['CONTENT_LENGTH'] = value
    when 'content-type'
      env['CONTENT_TYPE'] = value
    end
    env['HTTP_' + header.gsub(/\-/, "_").upcase] = value
  end
  request = Rack::Request.new(env)
  return request
end

.transmit(request, connection = nil) ⇒ Object

Raises:

  • (NotImplementedError)


91
92
93
94
# File 'lib/httpadapter/adapters/rack.rb', line 91

def self.transmit(request, connection=nil)
  raise NotImplementedError,
    'No HTTP client implementation available to transmit a Rack::Request.'
end

Instance Method Details

#to_aryObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/httpadapter/adapters/rack.rb', line 31

def to_ary
  method = @request.request_method.to_s.upcase
  uri = Addressable::URI.parse(@request.url.to_s).normalize.to_s
  headers = []
  @request.env.each do |parameter, value|
    next if parameter !~ /^HTTP_/
    # Ugh, lossy canonicalization again
    header = (parameter.gsub(/^HTTP_/, '').split('_').map do |chunk|
      chunk.capitalize
    end).join('-')
    headers << [header, value]
  end
  return [method, uri, headers, @request.body]
end