Class: AfterShip::V4::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/aftership/v4/base.rb

Direct Known Subclasses

Courier, LastCheckpoint, Tracking

Defined Under Namespace

Classes: AfterShipError

Constant Summary collapse

MAX_TRIAL =
3
CALL_SLEEP =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_verb_method, end_point, query = {}, body = {}) ⇒ Base

Returns a new instance of Base.


14
15
16
17
18
19
20
21
22
# File 'lib/aftership/v4/base.rb', line 14

def initialize(http_verb_method, end_point, query = {}, body = {})
  @http_verb_method = http_verb_method
  @end_point = end_point
  @query = query
  @body = body
  @trial = 0

  @client = HTTPClient.new
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body


9
10
11
# File 'lib/aftership/v4/base.rb', line 9

def body
  @body
end

#end_pointObject (readonly)

Returns the value of attribute end_point


9
10
11
# File 'lib/aftership/v4/base.rb', line 9

def end_point
  @end_point
end

#http_verb_methodObject (readonly)

Returns the value of attribute http_verb_method


9
10
11
# File 'lib/aftership/v4/base.rb', line 9

def http_verb_method
  @http_verb_method
end

#queryObject (readonly)

Returns the value of attribute query


9
10
11
# File 'lib/aftership/v4/base.rb', line 9

def query
  @query
end

Instance Method Details

#callObject


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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/aftership/v4/base.rb', line 24

def call

  header = {'aftership-api-key' => AfterShip.api_key, 'Content-Type' => 'application/json'}

  parameters = {
      :query => query,
      :body => body.to_json,
      :header => header
  }

  cf_ray = ''
  response = nil

  loop do
    response = @client.send(http_verb_method, url, parameters)

    if response.headers
      cf_ray = response.headers['CF-RAY']
    end


    if response.body
      begin
        response = JSON.parse(response.body)
        @trial = MAX_TRIAL + 1
      rescue
        @trial += 1

        sleep CALL_SLEEP

        response = {
            :meta => {
                :code => 500,
                :message => 'Something went wrong on AfterShip\'s end.',
                :type => 'InternalError'
            },
            :data => {
                :body => response.body,
                :cf_ray => cf_ray
            }
        }
      end
    else
      response = {
          :meta => {
              :code => 500,
              :message => 'Something went wrong on AfterShip\'s end.',
              :type => 'InternalError'
          },
          :data => {
          }
      }
    end

    break if @trial > MAX_TRIAL
  end

  response
end