Class: Typhoeus::Hydra

Inherits:
Object
  • Object
show all
Defined in:
lib/web/ext/typhoeus.rb

Instance Method Summary collapse

Instance Method Details

#initialize_with_web(options = {}) ⇒ Object Also known as: initialize

Thank you to the creators of Typhoeus for making this so easy to do.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/web/ext/typhoeus.rb', line 30

def initialize_with_web(options = {})
  initialize_without_web(options)
  # On cache set, record this if we should
  cache_setter do |req|
    web = Web::Faker.new req.method, req.url, req.body, req.headers
    if web.desired?
      res = req.response
      web.record res.code, res.body, res.headers_hash
    end
  end
  # On cache get, reconstruct the response and send it back
  cache_getter do |req|
    web = Web::Faker.new req.method, req.url, req.body, req.headers
    if web.desired? && web_response = web.response_for
      # put the headers back together, since we cache them as a dict
      h_str = web_response.headers ?
        web_response.headers.map { |k, v| "#{k}: #{v}" }.join("\n") : ''
      # and then reconstruct the response
      response = Typhoeus::Response.new({
        :code => web_response.code,
        :headers => h_str,
        :body => web_response.body
      })
      response.instance_variable_set :@cached, true
      response
    end
  end
end