lib/vkontakte_api/api.rb in vkontakte_api-0.2.1 vs lib/vkontakte_api/api.rb in vkontakte_api-1.0.rc
- old
+ new
@@ -1,51 +1,39 @@
module VkontakteApi
- # A low-level module which handles the requests to VKontakte and returns their results as hashes with symbolized keys.
+ # A low-level module which handles the requests to VKontakte API and returns their results as mashes.
#
- # It uses Faraday underneath the hood.
+ # It uses Faraday with middleware underneath the hood.
module API
- BASE_HOST = 'https://api.vkontakte.ru'
- BASE_URL = '/method/'
+ # URL prefix for calling API methods.
+ URL_PREFIX = 'https://api.vkontakte.ru/method'
class << self
- # Main interface method.
+ # API method call.
# @param [String] method_name A full name of the method.
- # @param [Hash] args Method arguments including the access token.
- # @return [Hash] The result of the method call.
- # @raise [VkontakteApi::Error] raised when VKontakte returns an error.
- def call(method_name, args = {}, &block)
- connection = Faraday.new(:url => BASE_HOST) do |builder|
- builder.adapter(VkontakteApi.adapter)
- end
-
- url = url_for(method_name, args)
- body = connection.get(url).body
- response = Yajl::Parser.parse(body, :symbolize_keys => true)
-
- if response.has_key?(:error)
- raise VkontakteApi::Error.new(response[:error])
- else
- response[:response]
- end
+ # @param [Hash] args Method arguments.
+ # @param [String] token The access token.
+ # @return [Hashie::Mash] Mashed server response.
+ def call(method_name, args = {}, token = nil)
+ flat_arguments = Utils.flatten_arguments(args)
+ connection(:url => URL_PREFIX, :token => token).get(method_name, flat_arguments).body
end
- private
- def url_for(method_name, arguments)
- flat_arguments = flatten_arguments(arguments)
- "#{BASE_URL}#{method_name}?#{flat_arguments.to_param}"
- end
-
- def flatten_arguments(arguments)
- arguments.inject({}) do |flat_args, (arg_name, arg_value)|
- flat_args[arg_name] = if arg_value.respond_to?(:join)
- # if value is an array, we join it with a comma
- arg_value.join(',')
- else
- # otherwise leave it untouched
- arg_value
- end
-
- flat_args
+ # Faraday connection.
+ # @param [Hash] options Connection options.
+ # @option options [String] :url Connection URL (either full or just prefix).
+ # @option options [String] :token OAuth2 access token (not used if omitted).
+ # @return [Faraday::Connection] Created connection.
+ def connection(options = {})
+ url = options.delete(:url)
+ token = options.delete(:token)
+
+ Faraday.new(url) do |builder|
+ builder.request :oauth2, token unless token.nil?
+ builder.request :multipart
+ builder.response :vk_logger
+ builder.response :mashify
+ builder.response :oj, :preserve_raw => true
+ builder.adapter VkontakteApi.adapter
end
end
end
end
end