Class: Rockette::Rester

Inherits:
Object
  • Object
show all
Defined in:
lib/rockette/rester.rb

Overview

configurable rest-client calls with error handling and auto retries

Constant Summary collapse

VERBS =
{
  "delete" => :Delete,
  "get" => :Get,
  "post" => :Post,
  "put" => :Put
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(headers: {}, meth: "Get", params: {}, url: "https://array/", config: {}) ⇒ Rester

Returns a new instance of Rester.



13
14
15
16
17
18
19
20
# File 'lib/rockette/rester.rb', line 13

def initialize(headers: {}, meth: "Get", params: {}, url: "https://array/", config: {})
  @headers = headers
  @meth    = meth
  @params  = params
  @url     = url
  @config = config
  @config["timeout"] = @config["timeout"] ||= 30
end

Instance Method Details



35
36
37
38
39
40
41
42
43
44
# File 'lib/rockette/rester.rb', line 35

def cookie
  if @url =~ %r{auth/session}
    response = make_call
    raise "There was an issue getting a cookie!" unless response.code == 200

    (response.cookies.map { |key, val| "#{key}=#{val}" })[0]
  else
    error_text("cookie", @url.to_s, "auth/session")
  end
end

#make_callObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rockette/rester.rb', line 22

def make_call
  response = RestClient::Request.execute(headers: @headers,
                                         method: VERBS[@meth.downcase], payload: @params,
                                         timeout: @config["timeout"], url: @url, verify_ssl: false)
rescue SocketError, IOError => e
  puts "#{e.class}: #{e.message}"
  nil
rescue StandardError => e
  e.response
else
  response
end

#rest_try(tries = 3) ⇒ Object

use rest-client with retry



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rockette/rester.rb', line 47

def rest_try(tries = 3)
  tries.times do |i|
    response = make_call
    unless response.nil?
      break response if (200..299).include? response.code
      break response if i > 1
    end
    puts "Failed #{@meth} on #{@url}, retry...#{i + 1}"
    sleep 3 unless i > 1
    return nil if i > 1 # Handles socket errors, etc. where there is no response.
  end
end