Class: Ya::Direct::Gateway

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

Constant Summary collapse

URLS =
{
  production: "https://soap.direct.yandex.ru/json-api/v4/",
  sandbox: "https://api-sandbox.direct.yandex.ru/json-api/v4/"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, config, mode) ⇒ Gateway

Returns a new instance of Gateway.



11
12
13
14
# File 'lib/ya_direct_api/gateway.rb', line 11

def initialize(env, config, mode)
  @url = URLS[mode]
  @config = config
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



4
5
6
# File 'lib/ya_direct_api/gateway.rb', line 4

def url
  @url
end

Instance Method Details

#get_data(method, params) ⇒ Object



44
45
46
47
48
49
# File 'lib/ya_direct_api/gateway.rb', line 44

def get_data(method, params)
  response = request(method, params)
  parsed_response = JSON.parse(response)
  validate_response!(parsed_response)
  parsed_response
end

#request(method, params) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ya_direct_api/gateway.rb', line 26

def request(method, params)
  url = URI.parse(@url)

  request = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})
  request.body = request_options(method, params).to_json

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  response = http.request(request)

  if response.kind_of? Net::HTTPSuccess
    return response.body
  else
    raise response.inspect
  end
end

#request_options(method, params) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/ya_direct_api/gateway.rb', line 16

def request_options(method, params)
  {
    locale: @config[:locale],
    login: @config[:login],
    application_id: @config[:app_id],
    token: @config[:token],
    method: method
  }.merge(params)
end

#validate_response!(response) ⇒ Object



51
52
53
54
55
# File 'lib/ya_direct_api/gateway.rb', line 51

def validate_response!(response)
  if response.has_key?('error_code')
    raise Ya::Direct::Exception.new(response['error_detail'], response['error_str'], response['error_code'])
  end
end