Class: BulletProofJson::Provider

Inherits:
Object
  • Object
show all
Defined in:
lib/bullet_proof_json/provider.rb

Constant Summary collapse

DEFAULT_MAX_ATTEMPTS =
3
DEFAULT_SLEEP_TIME =
1

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, logger = ConsoleLogger.new) ⇒ Provider

Returns a new instance of Provider.



10
11
12
13
# File 'lib/bullet_proof_json/provider.rb', line 10

def initialize(api_key=nil, logger=ConsoleLogger.new)
  @api_key = api_key
  @logger = logger
end

Instance Method Details

#get(uri_string = "", options = {max_attempts: 3, sleep_time: 1}, page = nil) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/bullet_proof_json/provider.rb', line 15

def get(uri_string = "", options = {max_attempts: 3, sleep_time: 1}, page = nil)
  json = nil

  sleep_time    = options[:sleep_time] || DEFAULT_SLEEP_TIME
  max_attempts  = options[:max_attempts] || DEFAULT_MAX_ATTEMPTS

  begin
    attempts ||= 1
    uri = URI(uri_string)
    http_headers = {}
    http_headers["Authorization"] = "Bearer #{@api_key}" unless @api_key.nil?
    http_headers["User-Agent"] = user_agent
    response = ::Net::HTTP.get(uri, http_headers)
    json = JSON(response)

  rescue ::Net::ReadTimeout => e
    @logger.error(self.class.name, " #{page.nil? ? "" : (page.to_s + ":")} #{e}\n#{uri_string}")
    if (attempts += 1) <= max_attempts
      @logger.debug(self.class.name, "\tAttempt no. #{attempts} ...")
      sleep sleep_time
      retry
    else
      @logger.error(self.class.name, "\tGiving up!!!")
      raise ProviderError.new("Giving up after Net::ReatTimeout and #{attempts} attempts!")
    end

  rescue ::Net::OpenTimeout => e
    @logger.error(self.class.name, " #{page.nil? ? "" : (page.to_s + ":")} #{e}\n#{uri_string}")
    if (attempts += 1) <= max_attempts
      @logger.debug(self.class.name, "\tAttempt no. #{attempts} ...")
      sleep sleep_time
      retry
    else
      @logger.error(self.class.name,  "\tGiving up!!!")
      raise ProviderError.new("Giving up after Net::OpenTimeout and #{attempts} attempts!")
    end

  rescue ::JSON::ParserError => e
    @logger.error(self.class.name, " #{page.nil? ? "" : (page.to_s + ":")} #{e}\n#{uri_string}")

    if (attempts += 1) <= max_attempts
      @logger.debug(self.class.name,  "\tAttempt no. #{attempts} ...")
      sleep sleep_time
      retry
    else
      @logger.error(self.class.name, "\tGiving up!!!")
      raise ProviderError.new("Giving up after JSON::ParserError and #{attempts} attempts!")
    end
  end
  json
end