Class: Alice::Adapter::Typhoeus

Inherits:
Middleware show all
Defined in:
lib/alice/adapter/typhoeus.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Middleware

#create_form_params, #full_path_for, #initialize, loaded?, #process_body_for_request

Constructor Details

This class inherits a constructor from Alice::Middleware

Class Method Details

.setup_parallel_manager(options = {}) ⇒ Object



6
7
8
# File 'lib/alice/adapter/typhoeus.rb', line 6

def self.setup_parallel_manager(options = {})
  options.empty? ? ::Typhoeus::Hydra.hydra : ::Typhoeus::Hydra.new(options)
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/alice/adapter/typhoeus.rb', line 16

def call(env)
  process_body_for_request(env)

  hydra = env[:parallel_manager] || self.class.setup_parallel_manager
  req   = ::Typhoeus::Request.new env[:url].to_s, 
    :method  => env[:method],
    :body    => env[:body],
    :headers => env[:request_headers]

  req.on_complete do |resp|
    env.update \
      :status           => resp.code,
      :response_headers => parse_response_headers(resp.headers),
      :body             => resp.body
    env[:response].finish(env)
  end

  hydra.queue req

  if !env[:parallel_manager]
    hydra.run
  end

  @app.call env
rescue Errno::ECONNREFUSED
  raise Error::ConnectionFailed, "connection refused"
end

#in_parallel(options = {}) ⇒ Object



44
45
46
47
48
49
# File 'lib/alice/adapter/typhoeus.rb', line 44

def in_parallel(options = {})
  @hydra = ::Typhoeus::Hydra.new(options)
  yield
  @hydra.run
  @hydra = nil
end

#parse_response_headers(header_string) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/alice/adapter/typhoeus.rb', line 51

def parse_response_headers(header_string)
  return {} unless header_string && !header_string.empty?
  Hash[*header_string.split(/\r\n/).
    tap  { |a|      a.shift           }. # drop the HTTP status line
    map! { |h|      h.split(/:\s+/,2) }. # split key and value
    map! { |(k, v)| [k.downcase, v]   }.flatten!]
end