Class: Http::Agent

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_options = {}) ⇒ Agent

Returns a new instance of Agent.



8
9
10
11
# File 'lib/allegro/http.rb', line 8

def initialize(_options = {})
  @logger = Logger.new(STDOUT)
  @options = _options
end

Instance Attribute Details

#authorizedObject (readonly)

Returns the value of attribute authorized.



6
7
8
# File 'lib/allegro/http.rb', line 6

def authorized
  @authorized
end

#loggerObject

Returns the value of attribute logger.



5
6
7
# File 'lib/allegro/http.rb', line 5

def logger
  @logger
end

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/allegro/http.rb', line 5

def options
  @options
end

Instance Method Details

#fetch(uri, params = {}) ⇒ Object

TODO: split to more atomic methods fe: handle_error, prepare request, etc.



14
15
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
48
49
50
51
# File 'lib/allegro/http.rb', line 14

def fetch(uri, params = {})
  uri = URI(uri)
  body = []
  begin
    session = Net::HTTP.new(uri.host, uri.port)
    session.use_ssl = uri.scheme == 'https'
    response = session.start do |http|
      request = build_request(uri, params)
      begin
        http.request(request) do |resp|
          resp.read_body do |segment|
            body << segment
          end
        end
      rescue StandardError => e
        logger.error e.message
      ensure
        body = body.join('')
      end
    end
    case response
    when Net::HTTPSuccess
      body = parse_body(body, response.content_type)
    when Net::HTTPRedirection
      raise StandardError, response.message
    else
      body = parse_body(body, response.content_type)
      return body if body.is_a?(Hash)

      raise StandardError, response.message
    end
  rescue StandardError => e
    logger.error e.message
    body = []
    raise e
  end
  body
end