Class: EasyManageClient::Core

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_manage_client/core.rb

Overview

Core

Direct Known Subclasses

Downloader

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(profile: :default) ⇒ Core

Returns a new instance of Core.



7
8
9
10
11
12
13
14
# File 'lib/easy_manage_client/core.rb', line 7

def initialize(profile: :default)
  self.profile = profile
  # Firstly, create a connection object.
  self.connection = Faraday.new(
    url: ::EasyManageClient.configuration(profile).root_url,
    headers: headers, params: params
  )
end

Instance Attribute Details

#connectionObject

Returns the value of attribute connection.



6
7
8
# File 'lib/easy_manage_client/core.rb', line 6

def connection
  @connection
end

#profileObject

Returns the value of attribute profile.



6
7
8
# File 'lib/easy_manage_client/core.rb', line 6

def profile
  @profile
end

#responseObject

Returns the value of attribute response.



6
7
8
# File 'lib/easy_manage_client/core.rb', line 6

def response
  @response
end

#successObject

Returns the value of attribute success.



6
7
8
# File 'lib/easy_manage_client/core.rb', line 6

def success
  @success
end

Instance Method Details

#generate_bearer_tokenObject

Generate Bearer token from configuration.



50
51
52
# File 'lib/easy_manage_client/core.rb', line 50

def generate_bearer_token
  "Bearer #{::EasyManageClient.configuration(profile).auth_token}"
end

#handle_response(resp) ⇒ Object

Response is parsed and checked here.



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/easy_manage_client/core.rb', line 32

def handle_response(resp)
  self.response = JSON.parse(resp.body, symbolize_names: true)

  # :content and :reference must be included in response.
  if response.keys.include?(:content) && response.keys.include?(:reference)
    return
  end

  # :content or :reference not included.
  raise ::EasyManageClient::InvalidResponseContent
end

#headersObject

Headers prepared here.



45
46
47
# File 'lib/easy_manage_client/core.rb', line 45

def headers
  { 'Authorization' => generate_bearer_token }
end

#paramsObject

Parameters are prepared here.



55
56
57
# File 'lib/easy_manage_client/core.rb', line 55

def params
  { version: ::EasyManageClient.configuration(profile).extension }
end

#performObject

Call the api and process the response.



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/easy_manage_client/core.rb', line 17

def perform
  resp = connection.get(request_uri)
  handle_response(resp)
  # If server returns 200, everything is OK.
  self.success = resp.status == 200
rescue Faraday::Error => e
  self.response = { message: e.message }
  self.success = false
rescue JSON::ParserError, ::EasyManageClient::InvalidResponseContent
  # Response cannot be handled.
  self.response = { message: 'Invalid response from the server.' }
  self.success = false
end