Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

@ exceptions

  • Loading branch information...
commit 2605e627daef08261101125b44488fd074c251b5 1 parent 05ed1d8
Andrew Zinenko authored
View
4 Gemfile.lock
@@ -6,8 +6,6 @@ PATH
faraday (~> 0.8.4)
faraday_middleware (~> 0.8.8)
multi_json (~> 1.3.6)
- transformer (~> 0.3.0)
- unicode_utils (~> 1.3.0)
GEM
remote: http://rubygems.org/
@@ -42,11 +40,9 @@ GEM
oj (1.0.6)
patron (0.4.18)
rake (0.8.7)
- transformer (0.3.0)
typhoeus (0.4.2)
ffi (~> 1.0)
mime-types (~> 1.18)
- unicode_utils (1.3.0)
webmock (1.8.10)
addressable (>= 2.2.7)
crack (>= 0.1.7)
View
9 lib/vk-ruby.rb
@@ -5,12 +5,7 @@
require 'faraday'
require 'faraday_middleware'
-require 'transformer'
require 'multi_json'
-require 'yaml'
-require 'cgi'
-require 'forwardable'
-require 'openssl'
require 'attr_configurable'
# Register multi_json parser.
@@ -18,6 +13,4 @@
MultiJson.load(body) unless body.strip.empty?
end
-%w(validate_utf normalize_utf vk_logger).each{|lib| require "vk-ruby/middleware/response/#{lib}"}
-
-%w(namespace utils core application secure serverside standalone vk_exception version).each{|lib| require "vk-ruby/#{lib}"}
+%w(namespace utils middleware/middleware core application secure serverside standalone vk_exception version).each { |lib| require "vk-ruby/#{lib}" }
View
4 lib/vk-ruby/application.rb
@@ -7,9 +7,9 @@ class VK::Application
# The duration of the token after authorization
attr_accessor :expires_in
- # A new VK::Application instan.
+ # A new VK::Application instance.
def initialize(params = {})
- params.each{|k,v| instance_variable_set(:"@#{k}", v) }
+ params.each { |k,v| send("#{k}=", v) }
end
end
View
67 lib/vk-ruby/core.rb
@@ -1,5 +1,7 @@
# encoding: UTF-8
+require 'openssl'
+
module VK
module Core
extend ::Configurable
@@ -111,10 +113,11 @@ def authorized?
# @raise an appropriate connection error if unable to make the request to vk.com.
# @raise if vk.com return json with key error.
- def vk_call(method_name, params = {})
- response = request("/method/#{method_name}", params || {})
+ def vk_call(method_name, params)
+ params ||= {}
+ params[:access_token] ||= self.access_token if self.access_token
- raise VK::ApiException.new(method_name, response.body) if response.body['error']
+ response = request("/method/#{method_name}", params)
response.body['response']
end
@@ -138,8 +141,10 @@ def faraday_middleware
faraday.request :multipart
faraday.request :url_encoded
- faraday.response :json, content_type: /\bjson$/
- # faraday.response :vk_logger, self.logger
+ faraday.response :api_errors
+ faraday.response :json, content_type: /\bjson$/
+ faraday.response :http_errors
+ faraday.response :vk_logger, self.logger
faraday.adapter self.adapter
end
@@ -186,33 +191,35 @@ def upload(params = {})
# @raise [VK::AuthorizeException] if vk.com return json with key error.
def authorize(params = {})
- raise 'undefined application id' unless self.app_id
- raise 'undefined application secret' unless self.app_secret
+ fail ArgumentError, 'You should pass :app_id parameter' unless self.app_id
+ fail ArgumentError, 'You should pass :app_secret parameter' unless self.app_secret
- params[:save].nil? ? (params[:save] = true) : (params[:save] = false)
+ params[:save] ||= true
params[:type] ||= :serverside
options = case params[:type]
- when :serverside
- {host: 'https://oauth.vk.com',
- client_id: self.app_id,
- client_secret: self.app_secret,
- code: params[:code],
- redirect_uri: (params[:redirect_uri] || self.redirect_url),
- verb: :get}
- when :secure
- {host: 'https://oauth.vk.com',
- client_id: self.app_id,
- client_secret: self.app_secret,
- grant_type: :client_credentials,
- verb: :get}
- end
+ when :serverside
+ {host: 'https://oauth.vk.com',
+ client_id: self.app_id,
+ client_secret: self.app_secret,
+ code: params[:code],
+ redirect_uri: (params[:redirect_uri] || self.redirect_url),
+ verb: :get}
+ when :secure
+ {host: 'https://oauth.vk.com',
+ client_id: self.app_id,
+ client_secret: self.app_secret,
+ grant_type: :client_credentials,
+ verb: :get}
+ end
response = request("/access_token", options)
- raise VK::AuthorizeException.new(response) if response.body['error']
-
- response.body.each{|k,v| instance_variable_set(:"@#{k}", v) } if params[:save]
+ if params[:save]
+ response.body.each do |k,v|
+ instance_variable_set("@#{k}", v) if respond_to?(k)
+ end
+ end
response.body
end
@@ -222,17 +229,11 @@ def authorize(params = {})
# @private
def request(path, options = {})
host = options.delete(:host) || 'https://api.vk.com'
- verb = (options.delete(:verb) || self.verb).downcase.to_sym
-
- options[:access_token] ||= self.access_token if host == 'https://api.vk.com' && self.access_token
+ verb = options.delete(:verb) || self.verb
params, body = http_params(verb, options)
- response = Faraday.new(host, params, &faraday_middleware).send(verb, path, body)
-
- raise VK::BadResponseException.new(response, verb, path, options) if response.status.to_i != 200
-
- response
+ Faraday.new(host, params, &faraday_middleware).send(verb, path, body)
end
# @private
View
18 lib/vk-ruby/middleware/middleware.rb
@@ -0,0 +1,18 @@
+# encoding: UTF-8
+
+module VK
+ module Middleware
+ module Response
+ end
+ end
+
+ MW = Middleware
+end
+
+%w(validate_utf normalize_utf vk_logger http_errors api_errors).each { |lib| require "vk-ruby/middleware/response/#{lib}"}
+
+Faraday.register_middleware :response, http_errors: VK::MW::Response::HttpErrors
+Faraday.register_middleware :response, api_errors: VK::MW::Response::ApiErrors
+Faraday.register_middleware :response, vk_logger: VK::MW::Response::VkLogger
+Faraday.register_middleware :response, normalize_utf: VK::MW::Response::NormalizeUtf
+Faraday.register_middleware :response, validate_utf: VK::MW::Response::ValidateUtf
View
20 lib/vk-ruby/middleware/response/api_errors.rb
@@ -0,0 +1,20 @@
+# encoding: UTF-8
+
+class VK::MW::Response::ApiErrors < Faraday::Response::Middleware
+
+ def call(environment)
+ @app.call(environment).on_complete do |env|
+ response = env[:response]
+
+ if response.body.has_key?('error')
+ if env[:url].host == 'oauth.vk.com'
+ fail VK::AuthorizeException.new response.body
+ else
+ method_name = env[:url].path.split('/').last.inspect
+ fail VK::ApiException.new(method_name, response.body)
+ end
+ end
+ end
+ end
+
+end
View
14 lib/vk-ruby/middleware/response/http_errors.rb
@@ -0,0 +1,14 @@
+# encoding: UTF-8
+
+class VK::MW::Response::HttpErrors < Faraday::Response::Middleware
+
+ def call(environment)
+ @app.call(environment).on_complete do |env|
+
+ if !env[:response].success?
+ fail VK::BadResponseException.new(env[:response])
+ end
+ end
+ end
+
+end
View
29 lib/vk-ruby/middleware/response/normalize_utf.rb
@@ -1,20 +1,21 @@
-require "unicode_utils"
+# encoding: UTF-8
-module Faraday
- class Response::NormalizeUtf < Response::Middleware
+class VK::MW::Response::NormalizeUtf < Faraday::Response::Middleware
- def initialize(app)
- super(app)
- end
+ dependency 'unicode_utils'
- def call(environment)
- @app.call(environment).on_complete do |env|
- env[:body] = UnicodeUtils.nfkd(env[:body])
- env
- end
- end
+ attr_accessor :ntype
+ def initialize(app, t = :nfkd)
+ self.ntype = t
+ super(app)
+ end
+
+ def call(environment)
+ @app.call(environment).on_complete do |env|
+ env[:body] = UnicodeUtils.send(ntype, env[:body])
+ env
+ end
end
-end
-Faraday.register_middleware :response, normalize_utf: Faraday::Response::NormalizeUtf
+end
View
29 lib/vk-ruby/middleware/response/validate_utf.rb
@@ -1,24 +1,19 @@
-require "unicode_utils"
+# encoding: UTF-8
-module Faraday
- class Response::ValidateUtf < Response::Middleware
+class VK::MW::Response::ValidateUtf < Faraday::Response::Middleware
- def initialize(app)
- super(app)
- end
-
- def call(environment)
- @app.call(environment).on_complete do |env|
-
- if (env[:body] = env[:body].force_encoding('UTF-8')).valid_encoding?
- env[:body] = env[:body].chars.select{|i| i.valid_encoding?}.join
- end
+ def initialize(app)
+ super(app)
+ end
- env
+ def call(environment)
+ @app.call(environment).on_complete do |env|
+ if (env[:body] = env[:body].force_encoding('UTF-8')).valid_encoding?
+ env[:body] = env[:body].chars.select{|i| i.valid_encoding?}.join
end
+
+ env
end
-
end
-end
-Faraday.register_middleware :response, validate_utf: Faraday::Response::ValidateUtf
+end
View
63 lib/vk-ruby/middleware/response/vk_logger.rb
@@ -1,47 +1,46 @@
-require 'forwardable'
+# encoding: UTF-8
-module Faraday
- class Response::VkLogger < Response::Middleware
- extend Forwardable
+class VK::MW::Response::VkLogger < Faraday::Response::Middleware
+ extend Forwardable
- def initialize(app, logger = nil)
- super(app)
+ dependency 'cgi'
+ dependency 'forwardable'
- @logger = logger || begin
- require 'logger'
- ::Logger.new(STDOUT)
- end
- end
+ def_delegators :@logger, :debug, :debug?, :error?, :info, :warn, :error, :fatal
- def_delegators :@logger, :debug, :debug?, :error?, :info, :warn, :error, :fatal
+ def initialize(app, logger = nil)
+ super(app)
- def call(env)
- if debug?
- method = env[:url].path.split('/').reject(&:empty?).last
+ @logger = !logger.nil? || begin
+ require 'logger'
+ ::Logger.new(STDOUT)
+ end
+ end
- params = if env[:method] == :get
- CGI.unescape env[:url].query
- else env[:method]
- CGI.unescape env[:body]
- end
+ def call(env)
+ if debug?
+ method = env[:url].path.split('/').reject(&:empty?).last
- debug "request #{method} -> #{params}"
- end
+ params = if env[:method] == :get
+ CGI.unescape env[:url].query
+ else env[:method]
+ CGI.unescape env[:body]
+ end
- super
+ debug "request #{method} -> #{params}"
end
- def on_complete(env)
- if debug?
- method = env[:url].path.split('/').reject(&:empty?).last
+ super
+ end
- params = CGI.unescape env[:body]
+ def on_complete(env)
+ if debug?
+ method = env[:url].path.split('/').reject(&:empty?).last
- debug "response #{method} <- #{env[:status].to_s.upcase} : #{params}"
- end
- end
+ params = CGI.unescape env[:body]
+ debug "response #{method} <- #{env[:status].to_s.upcase} : #{params}"
+ end
end
-end
-Faraday.register_middleware :response, vk_logger: Faraday::Response::VkLogger
+end
View
2  lib/vk-ruby/serverside.rb
@@ -32,7 +32,7 @@ def authorize(code, auto_save = true)
response = request("/access_token", params)
- raise VK::AuthorizeException.new(response) if response.body['error']
+ fail VK::AuthorizeException.new(response) if response.body['error']
response.body.each{|k,v| instance_variable_set(:"@#{k}", v) } if auto_save
View
48 lib/vk-ruby/vk_exception.rb
@@ -2,33 +2,51 @@
module VK
- class ApiException < Exception
- attr_reader :vk_method, :error_code, :error_msg
+ class Error < StandardError
+ end
+
+ class ApiException < Error
+
+ attr_reader :vk_method, :code, :discription
def initialize(api_method, error_hash)
- @vk_method, @error_code = api_method, error_hash['error']['error_code'].to_i
- @error_msg = "Error #{@error_code} in #{@vk_method} - #{error_hash['error']['error_msg']}"
- super @error_msg
+ @vk_method = api_method
+ @code = error_hash['error']['error_code'].to_i
+ @discription = error_hash['error']['error_msg']
+ end
+
+ def to_s
+ "Error #@code in #@vk_method : #@discription"
end
end
- class AuthorizeException < Exception
- attr_reader :error, :error_msg
+ class AuthorizeException < Error
+
+ attr_reader :error, :description
def initialize(error_hash)
- @error, @error_msg = error_hash['error'], "Error #{@error} - #{error_hash['error_description']}"
- super @error_msg
+ @error = error_hash['error']
+ @description = error_hash['error_description']
+ end
+
+ def to_s
+ "Error #@error : #@description"
end
end
- class BadResponseException < Exception
- attr_reader :response, :params
+ class BadResponseException < Error
+
+ attr_reader :response
- def initialize(response, verbs, path, options)
- @response, @params = response, params
- @error_msg = "Bad response"
- super @error_msg
+ def initialize(response)
+ @response = response
+ super
end
+
+ def to_s
+ "Bad response (#{ response.status })"
+ end
+
end
end
View
35 tests/application_test.rb
@@ -4,7 +4,7 @@ class ApplicationTest < MiniTest::Unit::TestCase
def setup
@app ||= ::VK::Application.new app_id: :test_id, app_secret: :test_secret, access_token: :test_token
- create_stubs!
+ WebMock.reset!
end
def test_namespaces
@@ -16,34 +16,21 @@ def test_namespaces
end
end
- def test_requests
+ def test_get_requests
+ stubs_get!
+
each_methods do |method_name|
- params = random_params.merge!(access_token: :test_token)
-
- # # POST request
- assert_equal eval("@app.#{method_name}(params)"), params.stringify
-
- # # GET request
- params.merge(verb: :get)
- assert_equal eval("@app.#{method_name}(params)"), params.stringify
+ params = random_params.merge(verb: :get)
+ assert_equal eval("@app.#{method_name}(params)"), params.merge(access_token: :test_token).stringify
end
end
- def test_authorization
- params = {client_id: :test_id ,client_secret: :test_secret}
- assert_equal @app.authorize(params.merge type: :secure) , {"client_id"=>"test_id", "client_secret"=>"test_secret", "grant_type"=>"client_credentials"}
- assert_equal @app.authorize(params.merge type: :serverside, code: :test_code, redirect_uri: '--') ,{"client_id"=>"test_id", "client_secret"=>"test_secret", "code"=>"test_code", "redirect_uri" => '--'}
- end
+ def test_post_request
+ stubs_post!
- def test_bad_requests
- assert_raises(::VK::BadResponseException) do
- @app.getProfiles http_error: :error
- end
- end
-
- def test_api_errors
- assert_raises(::VK::ApiException) do
- @app.getProfiles error: :error
+ each_methods do |method_name|
+ params = random_params
+ assert_equal eval("@app.#{method_name}(params)"), params.merge(access_token: :test_token).stringify
end
end
View
23 tests/auth_test.rb
@@ -0,0 +1,23 @@
+require File.expand_path('../helpers', __FILE__)
+
+class AuthTest < MiniTest::Unit::TestCase
+
+ def setup
+ @app ||= ::VK::Application.new app_id: :test_id, app_secret: :test_secret, access_token: :test_token
+ WebMock.reset!
+ stubs_auth!
+ end
+
+ def test_serverside_authorization
+ params = {client_id: :test_id ,client_secret: :test_secret, type: :serverside, code: :test_code, redirect_uri: '--'}
+
+ assert_equal @app.authorize(params) ,{"client_id"=>"test_id", "client_secret"=>"test_secret", "code"=>"test_code", "redirect_uri" => '--'}
+ end
+
+ def test_secure_authorization
+ params = {client_id: :test_id ,client_secret: :test_secret, type: :secure}
+
+ assert_equal @app.authorize(params), {"client_id"=>"test_id", "client_secret"=>"test_secret", "grant_type"=>"client_credentials"}
+ end
+
+end
View
29 tests/exception_test.rb
@@ -0,0 +1,29 @@
+require File.expand_path('../helpers', __FILE__)
+
+class ExceptionTest < MiniTest::Unit::TestCase
+
+ def setup
+ @app ||= ::VK::Application.new app_id: :test_id, app_secret: :test_secret, access_token: :test_token
+ WebMock.reset!
+ end
+
+ def test_bad_requests
+ stubs_http_error!
+
+ assert_raises(::VK::BadResponseException) { @app.users.get }
+ end
+
+ def test_api_errors
+ stubs_api_error!
+
+ assert_raises(::VK::ApiException) { @app.users.get }
+ end
+
+ def test_auth_errors
+ stubs_auth_error!
+ params = {client_id: :test_id ,client_secret: :test_secret, type: :secure}
+
+ assert_raises(::VK::AuthorizeException) { @app.authorize(params) }
+ end
+
+end
View
43 tests/helpers.rb
@@ -7,32 +7,48 @@
if File.exists?("#{Dir.pwd}/config.yml")
YAML.load_file("#{Dir.pwd}/config.yml").each do |name, value|
- self.class.const_set name.upcase, value
+ self.class.const_set(name.upcase, value)
end
end
-def create_stubs!
+def stubs_get!
stub_request(:get, /https:\/\/api.vk.com\/method/).to_return(lambda { |request|
{
body: MultiJson.dump('response' => URI.parse(request.uri).query.to_params),
headers: {"Content-Type" => 'application/json'}
}
})
+end
+def stubs_post!
stub_request(:post, /https:\/\/api.vk.com\/method/).to_return(lambda { |request|
+ {
+ body: MultiJson.dump('response' => request.body.to_params),
+ headers: {"Content-Type" => 'application/json'}
+ }
+ })
+end
- body = request.body.to_params
- status = body.has_key?('http_error') ? 500 : 200
-
- response = body.has_key?('error') ? {'error' => {}} : {'response' => body}
-
+def stubs_http_error!
+ stub_request(:post, /https:\/\/api.vk.com\/method/).to_return(lambda { |request|
{
- body: MultiJson.dump(response),
+ body: MultiJson.dump('response' => request.body.to_params),
headers: {"Content-Type" => 'application/json'},
- status: status
+ status: 500
+ }
+ })
+end
+
+def stubs_api_error!
+ stub_request(:post, /https:\/\/api.vk.com\/method/).to_return(lambda { |request|
+ {
+ body: MultiJson.dump('error' => {'error_code' => 'code', 'error_msg' => 'message'}),
+ headers: {"Content-Type" => 'application/json'}
}
})
+end
+def stubs_auth!
stub_request(:get, /https:\/\/oauth.vk.com\/access_token/).to_return(lambda { |request|
{
body: MultiJson.dump(URI.parse(request.uri).query.to_params),
@@ -41,6 +57,15 @@ def create_stubs!
})
end
+def stubs_auth_error!
+ stub_request(:get, /https:\/\/oauth.vk.com\/access_token/).to_return(lambda { |request|
+ {
+ body: MultiJson.dump('error' => 'message', 'error_description' => 'discription'),
+ headers: {"Content-Type" => 'application/json'}
+ }
+ })
+end
+
class String
def to_params
self.split('&').inject({}) do |hash, element|
View
13 vk-ruby.gemspec
@@ -5,21 +5,22 @@ require 'vk-ruby/version'
Gem::Specification.new do |gem|
gem.name = "vk-ruby"
+
gem.version = VK::VERSION
+ gem.date = Time.now.strftime '%Y-%m-%d'
+
gem.authors = ["Andrew Zinenko"]
gem.email = "zinenkoan@gmail.com"
+ gem.homepage = "http://github.com/zinenko/vk-ruby"
+
gem.summary = "Ruby wrapper for vk.com API"
gem.description = " Ruby wrapper for vk.com API "
- gem.homepage = "http://github.com/zinenko/vk-ruby"
- gem.date = Time.now.strftime '%Y-%m-%d'
gem.licenses = ["MIT"]
- gem.add_runtime_dependency 'transformer', '~> 0.3.0'
- gem.add_runtime_dependency 'attr_configurable', '~> 0.1.0'
- gem.add_runtime_dependency 'multi_json', '~> 1.3.6'
gem.add_runtime_dependency 'faraday', '~> 0.8.4'
gem.add_runtime_dependency 'faraday_middleware', '~> 0.8.8'
- gem.add_runtime_dependency 'unicode_utils', '~> 1.3.0'
+ gem.add_runtime_dependency 'attr_configurable', '~> 0.1.0'
+ gem.add_runtime_dependency 'multi_json', '~> 1.3.6'
gem.add_runtime_dependency 'jruby-openssl', '~> 0.7.7' if RUBY_PLATFORM == 'java'
gem.add_development_dependency 'rake', '~> 0.8.7'
Please sign in to comment.
Something went wrong with that request. Please try again.