Class: Api

Inherits:
Object
  • Object
show all
Defined in:
lib/vk_cozy/api/api.rb

Constant Summary collapse

SCHEME =
'https'
HOST =
'api.vk.com'
PATH =
'/method/'
PORT =
443

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token, version = 5.92) ⇒ Api

Returns a new instance of Api.



14
15
16
17
# File 'lib/vk_cozy/api/api.rb', line 14

def initialize(access_token, version=5.92)
  @access_token = access_token
  @version = version
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, **kwargs) ⇒ Object



46
47
48
# File 'lib/vk_cozy/api/api.rb', line 46

def method_missing name, **kwargs
  return request(name.to_s.sub('_', '.'), kwargs)['response']
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



7
8
9
# File 'lib/vk_cozy/api/api.rb', line 7

def access_token
  @access_token
end

#versionObject

Returns the value of attribute version.



7
8
9
# File 'lib/vk_cozy/api/api.rb', line 7

def version
  @version
end

Instance Method Details

#request(method_vk, data) ⇒ Object



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

def request(method_vk, data)
  data = data.to_hash
  data = data.merge(v: version)
  data = data.merge(access_token: access_token)
  data.each do |argument, value|
    data[argument] = value.join(',') if value.is_a?(Array)
  end
  http_response = Net::HTTP.post_form(url_for_method(method_vk), data).body
  # return unless http_response.present?
  json_response = JSON.parse(http_response)
  if json_response['error']
    raise json_response['error']['error_msg']
  end
  json_response
end

#request_thr(method_vk, data) ⇒ Object



19
20
21
22
23
24
# File 'lib/vk_cozy/api/api.rb', line 19

def request_thr(method_vk, data)
  thr = Thread.new {
    request(method_vk, data)
  }
  thr.run
end

#url_for_method(method_vk) ⇒ Object



42
43
44
# File 'lib/vk_cozy/api/api.rb', line 42

def url_for_method(method_vk)
  URI.parse("#{SCHEME}://#{HOST}#{PATH}#{method_vk}")
end