Class: Rack::Client::Handler::EmHttp

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
DualBand
Defined in:
lib/rack/client/handler/em-http.rb

Instance Method Summary collapse

Methods included from DualBand

#call

Instance Method Details

#async_call(env) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rack/client/handler/em-http.rb', line 31

def async_call(env)
  request = Rack::Request.new(env)

  EM.schedule do
    em_http = connection(request.url).send(request.request_method.downcase, request_options(request))
    em_http.callback do
      yield parse(em_http).finish
    end

    em_http.errback do
      yield parse(em_http).finish
    end
  end
end

#connection(url) ⇒ Object



46
47
48
# File 'lib/rack/client/handler/em-http.rb', line 46

def connection(url)
  EventMachine::HttpRequest.new(url)
end

#normalize_headers(em_http) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/rack/client/handler/em-http.rb', line 73

def normalize_headers(em_http)
  headers = em_http.response_header

  headers['LOCATION'] = URI.parse(headers['LOCATION']).path if headers.include?('LOCATION')

  headers
end

#parse(em_http) ⇒ Object



68
69
70
71
# File 'lib/rack/client/handler/em-http.rb', line 68

def parse(em_http)
  body = em_http.response.empty? ? [] : StringIO.new(em_http.response)
  Response.new(em_http.response_header.status, Headers.new(em_http.response_header).to_http, body)
end

#request_options(request) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rack/client/handler/em-http.rb', line 50

def request_options(request)
  options = {}

  if request.body
    options[:body] = case request.body
                     when Array     then request.body.join
                     when StringIO  then request.body.string
                     when IO        then request.body.read
                     when String    then request.body
                     end
  end

  headers = Headers.from(request.env).to_http
  options[:head] = headers unless headers.empty?

  options
end

#sync_call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rack/client/handler/em-http.rb', line 19

def sync_call(env)
  raise("Synchronous API is not supported for EmHttp Handler without EM::Synchrony") unless defined?(EventMachine::Synchrony)

  request, fiber = Rack::Request.new(env), Fiber.current

  conn = connection(request.url).send(request.request_method.downcase.to_sym, request_options(request))
  conn.callback { fiber.resume(conn) }
  conn.errback  { fiber.resume(conn) }

  parse(Fiber.yield).finish
end