Class: Ac::Base

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

Constant Summary collapse

MAX_RETRIES =
3
SAVE_RESPONSES =
false

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token = nil) ⇒ Base

Returns a new instance of Base.



7
8
9
# File 'lib/ac/base.rb', line 7

def initialize access_token = nil
  @access_token = access_token
end

Instance Attribute Details

#token_expires_atObject (readonly)

Returns the value of attribute token_expires_at.



6
7
8
# File 'lib/ac/base.rb', line 6

def token_expires_at
  @token_expires_at
end

Instance Method Details

#access_tokenObject



11
12
13
14
# File 'lib/ac/base.rb', line 11

def access_token
  refresh_token if should_refresh?
  @access_token
end

#authenticate!(options) ⇒ Object



38
39
40
41
42
43
# File 'lib/ac/base.rb', line 38

def authenticate! options
  if access_token
    options[:headers] ||= {}
    options[:headers]["Authorization"] = "Bearer #{access_token}"
  end
end

#can_retry?(response) ⇒ Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/ac/base.rb', line 86

def can_retry? response
  response.timed_out? || response.code == 0 || response.code == 429 || response.code >= 500
end

#default_optionsObject



29
30
31
32
33
34
35
36
# File 'lib/ac/base.rb', line 29

def default_options
  {
    headers: {
      "Content-Type" => "application/json",
      "x-idempotency-key" => SecureRandom.uuid
    }
  }
end

#should_refresh?Boolean

Returns:

  • (Boolean)


16
17
18
19
# File 'lib/ac/base.rb', line 16

def should_refresh?
  return false unless respond_to?(:refresh_token)
  @access_token.blank? || @token_expires_at&.past?
end

#url(path) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/ac/base.rb', line 21

def url path
  if path.start_with?("http://") || path.start_with?("https://")
    path
  else
    File.join(self.class::BASE_URL, path)
  end
end

#validate(ac_object, block = nil) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/ac/base.rb', line 78

def validate ac_object, block=nil
  if block
    block.call ac_object rescue false
  else
    ac_object.response.success?
  end
end