Class: Gateway::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/gateway/client.rb

Overview

Client

Constant Summary collapse

METHOD_GET =

http method GET

'get'
METHOD_POST =

http method POST

'post'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, token, test = false) ⇒ Client

Initialize

Parameters:

Raises:



29
30
31
32
33
34
35
36
37
# File 'lib/gateway/client.rb', line 29

def initialize(request, token, test = false)
  Gateway.config = JSON.parse(YAML.load_file("#{Gateway.root}/gateway/config.yml").to_json, object_class: OpenStruct)
  @request       = request
  @token         = token
  @test          = test
  request_name   = request.class.name.split('::').last
  @config_data   = Gateway.config.api_methods[request_name]
  raise Gateway::StandardError.new("fill data in config.yml for method: #{request_name}") unless @config_data
end

Instance Attribute Details

#config_dataObject (readonly)

Returns the value of attribute config_data.



20
21
22
# File 'lib/gateway/client.rb', line 20

def config_data
  @config_data
end

#requestObject

Returns the value of attribute request.



19
20
21
# File 'lib/gateway/client.rb', line 19

def request
  @request
end

#testObject (readonly)

Returns the value of attribute test.



20
21
22
# File 'lib/gateway/client.rb', line 20

def test
  @test
end

Instance Method Details

#responseHash

Send request to gateway and take response from it

Returns:

  • (Hash)

    raw response from gateway



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/gateway/client.rb', line 44

def response
  # Rails.logger.debug('gateway request: ' + YAML::dump(request))
  query_params = {r: config_data.route}
  case config_data.http_method
    when METHOD_GET
      query_params.merge! request.attributes
      response = RestClient.get(url(query_params))
    when METHOD_POST
      response = RestClient.post(url(query_params), request.attributes, Authorization: @token)
    else
      raise Gateway::ArgumentError.new("http method #{config_data.http_method} is not supported")
  end
  return JSON.parse(response)
rescue RestClient::Exception => e
  response = JSON.parse e.response
  raise Gateway::StandardError.new(response['message'])
end

#url(query_params) ⇒ String

Generate url

Parameters:

  • query_params (Hash)

Returns:

  • (String)

    url with query params



70
71
72
73
74
# File 'lib/gateway/client.rb', line 70

def url(query_params)
  url = test ? Gateway.config.urls.test : Gateway.config.urls.production
  url += '?' + URI.encode_www_form(query_params) unless query_params.empty?
  url
end