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

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

Instance Method Summary collapse

Methods included from DualBand

#call

Constructor Details

#initialize(url) ⇒ EmHttp

Returns a new instance of EmHttp.



9
10
11
# File 'lib/rack/client/handler/em-http.rb', line 9

def initialize(url)
  @uri = URI.parse(url)
end

Instance Method Details

#async_call(env) ⇒ Object



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

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

  EM.schedule do
    em_http = connection(request.path).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(path) ⇒ Object



32
33
34
# File 'lib/rack/client/handler/em-http.rb', line 32

def connection(path)
  @connection ||= EventMachine::HttpRequest.new((@uri + path).to_s)
end

#normalize_headers(em_http) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/rack/client/handler/em-http.rb', line 56

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



51
52
53
54
# File 'lib/rack/client/handler/em-http.rb', line 51

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rack/client/handler/em-http.rb', line 36

def request_options(request)
  options = {}

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

  options
end

#sync_call(env) ⇒ Object



13
14
15
# File 'lib/rack/client/handler/em-http.rb', line 13

def sync_call(env)
  raise("Synchronous API is not supported for EmHttp Handler") unless block_given?
end