Class: Calpack::BaseController

Inherits:
Object
  • Object
show all
Defined in:
lib/calpack/controllers/base_controller.rb

Overview

Base controller.

Direct Known Subclasses

SimpleCalculatorController

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_client: nil, http_call_back: nil) ⇒ BaseController

Returns a new instance of BaseController.



11
12
13
14
15
16
17
18
# File 'lib/calpack/controllers/base_controller.rb', line 11

def initialize(http_client: nil, http_call_back: nil)
  @http_client = http_client || FaradayClient.new
  @http_call_back = http_call_back

  @global_headers = {
    'user-agent' => 'APIMATIC 2.0'
  }
end

Instance Attribute Details

#http_call_backObject

Returns the value of attribute http_call_back.



9
10
11
# File 'lib/calpack/controllers/base_controller.rb', line 9

def http_call_back
  @http_call_back
end

#http_clientObject

Returns the value of attribute http_client.



9
10
11
# File 'lib/calpack/controllers/base_controller.rb', line 9

def http_client
  @http_client
end

Instance Method Details

#execute_request(request, binary: false) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/calpack/controllers/base_controller.rb', line 28

def execute_request(request, binary: false)
  @http_call_back.on_before_request(request) if @http_call_back

  APIHelper.clean_hash(request.headers)
  request.headers = @global_headers.clone.merge(request.headers)

  response = if binary
               @http_client.execute_as_binary(request)
             else
               @http_client.execute_as_string(request)
             end
  context = HttpContext.new(request, response)

  @http_call_back.on_after_response(context) if @http_call_back

  context
end

#validate_parameters(args) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/calpack/controllers/base_controller.rb', line 20

def validate_parameters(args)
  args.each do |_name, value|
    if value.nil?
      raise ArgumentError, "Required parameter #{_name} cannot be nil."
    end
  end
end

#validate_response(context) ⇒ Object



46
47
48
49
# File 'lib/calpack/controllers/base_controller.rb', line 46

def validate_response(context)
  raise APIException.new 'HTTP Response Not OK', context unless
    context.response.status_code.between?(200, 208) # [200,208] = HTTP OK
end