Module: SmartVkApi::Call

Included in:
VK
Defined in:
lib/smart_vk_api/call.rb

Instance Method Summary collapse

Instance Method Details

#call(method_name, params = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/smart_vk_api/call.rb', line 3

def call(method_name, params = {})
  http(method_name, params) do |response|
    raise SmartVkApi::MethodCallError, response.body unless response.is_a?(Net::HTTPSuccess)
    json = response.body
    raise SmartVkApi::MethodCallError, 'Response could not be empty' if json.nil? || json.empty?
    parsed_json = JSON.parse(json, :symbolize_names => true)
    raise SmartVkApi::MethodCallError, json if is_error?(parsed_json)
    raise SmartVkApi::MethodCallError, 'Response should include key named :response' unless parsed_json.has_key?(:response)
    parsed_json[:response]
  end
end

#http(method_name, params = {}) ⇒ Object



15
16
17
18
19
20
# File 'lib/smart_vk_api/call.rb', line 15

def http(method_name, params = {})
  uri = URI(method_url(method_name, params))
  http = Net::HTTP.new(uri.host,uri.port)
  http.use_ssl = true
  block_given? ? yield(http.get(uri.request_uri, headers)) : http
end

#method_url(method_name, params = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/smart_vk_api/call.rb', line 22

def method_url(method_name, params = {})
  if method_name.nil? || method_name.empty?
    raise ArgumentError, 'Method name could not be empty'
  end
  if access_token && (params.nil? || !params.key?(:access_token))
    params ||= {}
    params[:access_token] = access_token
  end
  url = SmartVkApi::Constants::METHOD_CALL_URL + "/#{method_name}"
  url += "?#{URI.encode_www_form(params)}" if params && params.any?
  url
end