Class: Faraday::Adapter::Typhoeus

Inherits:
Middleware show all
Defined in:
lib/faraday/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 Faraday::Middleware

Class Method Details

.setup_parallel_manager(options = {}) ⇒ Object



6
7
8
# File 'lib/faraday/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
43
44
45
46
47
# File 'lib/faraday/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],
    :disable_ssl_peer_verification => (env[:ssl][:verify] == false)
  
  env_req = env[:request]
  req.timeout = req.connect_timeout = (env_req[:timeout] * 1000) if env_req[:timeout]
  req.connect_timeout = (env_req[:open_timeout] * 1000)          if env_req[:open_timeout]

  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



49
50
51
52
53
54
# File 'lib/faraday/adapter/typhoeus.rb', line 49

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

#parse_response_headers(header_string) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/faraday/adapter/typhoeus.rb', line 56

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