Class: Elekk::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/elekk/http.rb

Overview

All the web requests by Elekk go through here. It would be good to abstract this so it can use HTTP requesters other than Typhoeus someday.

Class Method Summary collapse

Class Method Details

.initObject

Do the set-up for Typhoeus and Memcache. Does not need to be called manually, it will set itself up when a request comes in.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/elekk/http.rb', line 13

def self.init
  if @initialized
    return
  end
  @initialized = true
  @hydra = Typhoeus::Hydra.new
  @cache = Memcached.new
  @hydra.cache_setter do |request|
    @cache.set request.cache_key, request.response, request.cache_timeout
  end
  @hydra.cache_getter do |request|
    @cache.get(request.cache_key) rescue nil
  end
end

.json(url, params = nil, opts = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/elekk/http.rb', line 52

def self.json(url, params=nil, opts={})
  request = self.request(url, params, opts)
  begin
    json = JSON request.response.body
    raise if json.nil?
  rescue
    $stderr.write "JSON Parse errors:\n"
    @cache.delete request.cache_key
  end
  json
end

.request(url, params = nil, opts = {}) ⇒ Object

Do a synchronous request for the base url with params added, default verb is GET



30
31
32
33
34
35
36
37
38
39
# File 'lib/elekk/http.rb', line 30

def self.request(url, params=nil, opts={})
  self.init
  opts = {:method => :get, :params => params, :timeout => 10000}.merge opts
  
  request = Typhoeus::Request.new(url, opts)
  
  @hydra.queue request
  @hydra.run
  request
end

.xml(url, params = nil, opts = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/elekk/http.rb', line 41

def self.xml(url, params=nil, opts={})
  request = self.request(url, params, opts)
  xml = Nokogiri::XML(request.response.body)
  if xml.errors.length > 0
    $stderr.write "XML Parse errors:\n"
    p xml.errors
    @cache.delete request.cache_key
  end
  xml
end