to_net_me_api 0.1.beta → 0.2

Sign up to get free protection for your applications and to get access to all the features.
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## 0.2 (26.09.2013)
2
+
3
+ * Добавлен модуль конфигурации
4
+
5
+ ## 0.1 (24.09.2013)
6
+
7
+ * первая стабильная версия
data/README.md CHANGED
@@ -1,4 +1,69 @@
1
- to_net_me_api
2
- =============
3
-
4
- ruby-адаптер для api.2net.me
1
+ ## to_net_me_api [![Gem Version](https://badge.fury.io/rb/to_net_me_api.png)](http://badge.fury.io/rb/to_net_me_api)
2
+
3
+
4
+
5
+
6
+
7
+ `to_net_me_api` - ruby-адаптер для api.2net.me. Он позволяет вызывать методы API.
8
+
9
+
10
+
11
+ ## Установка
12
+
13
+
14
+
15
+ ``` ruby
16
+
17
+ # Gemfile
18
+
19
+ gem 'to_net_me_api'
20
+
21
+ ```
22
+
23
+
24
+
25
+ или просто
26
+
27
+
28
+
29
+ ``` sh
30
+
31
+ $ gem install to_net_me_api
32
+
33
+ ```
34
+
35
+
36
+
37
+ ## Использование
38
+
39
+
40
+
41
+ ### Вызов методов
42
+
43
+
44
+
45
+ ``` ruby
46
+ require 'to_net_me_api' #=> true
47
+
48
+ # создаем клиент
49
+ @to_net_me = ToNetMeApi::Client.new('auth_key')
50
+ # и вызываем методы API
51
+ groups = @to_net_me.search.groups(:name=>'велосипеды',:vk=>'true')
52
+
53
+ # методы возвращают объект HTTParty
54
+ # в котором находится ответ от сервека api.2net.me
55
+ groups.parsed_response #=> {"message"=>{"vk"=>[7389, {"gid"=>52734067, "name"=>"Велосипеды"....
56
+
57
+ # в ruby принято использовать snake_case в названиях методов,
58
+ # поэтому search.groupsById становится search.groups_by_id
59
+ @to_net_me.search.groups_by_id(:gids=>'37856556',:soc=>'vk')
60
+
61
+ # если API 2net.me ожидает получить параметр в виде списка,
62
+ # разделенного запятыми, то его можно передать массивом
63
+ @to_net_me.search.groups_by_id(:gids=>'2net_me,37856556,38019449',:soc=>'vk')
64
+ ```
65
+ ### Документация
66
+
67
+ Документация к методам api находится [по адресу](http://api.2net.me/index/info).
68
+ Так же можно попробовать api через web-интерфейс [тут](http://api.2net.me/index).
69
+
@@ -0,0 +1,32 @@
1
+ require 'httparty'
2
+ require 'yaml'
3
+ require 'hashie'
4
+
5
+ require 'to_net_me_api/version'
6
+ require 'to_net_me_api/configuration'
7
+ require 'to_net_me_api/api'
8
+ require 'to_net_me_api/resolver'
9
+ require 'to_net_me_api/resolvable'
10
+ require 'to_net_me_api/client'
11
+ require 'to_net_me_api/namespace'
12
+ require 'to_net_me_api/method'
13
+
14
+
15
+ # Main module.
16
+ module ToNetMeApi
17
+ extend ToNetMeApi::Configuration
18
+ #extend VkontakteApi::Authorization
19
+ #extend VkontakteApi::Uploading
20
+
21
+ class << self
22
+ # Creates a short alias `TNM` for `ToNetMeApi` module.
23
+ def register_alias
24
+ Object.const_set(:TNM, ToNetMeApi)
25
+ end
26
+
27
+ # Removes the `TNM` alias.
28
+ def unregister_alias
29
+ Object.send(:remove_const, :TNM) if defined?(TNM)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,18 @@
1
+ # require 'httparty'
2
+ module ToNetMeApi
3
+ # Модуль обрабатывает запросы к API 2et.me и возвращает HTTParty объект .
4
+ module API
5
+
6
+ class << self
7
+
8
+ def call(attrs,options={},auth_key = nil)
9
+ @auth = {:auth_key => auth_key}
10
+ options.merge!(@auth)
11
+ HTTParty.get('http://api.2net.me/'+attrs,:query => options)
12
+ end
13
+
14
+ end
15
+ end
16
+
17
+ end
18
+
@@ -0,0 +1,81 @@
1
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/namespace'
2
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/resolvable'
3
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/resolver'
4
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/method'
5
+ module ToNetMeApi
6
+ # Класс, представляющий соединение с api.2net.me.
7
+ class Client
8
+ include Resolver
9
+
10
+ # Права доступа и их числовые значения.
11
+ SCOPE = {
12
+ root: 0,
13
+ admin: 1,
14
+ partner: 2,
15
+ user: 3,
16
+ unknown_auth_key: 4,
17
+
18
+ }
19
+
20
+ # ключ доступа к методам api
21
+ # @return [String]
22
+ attr_reader :auth_key
23
+ # Current user id.
24
+ # @return [Integer]
25
+ attr_reader :user_id
26
+ # время жизни auth_key
27
+ # @return [Time]
28
+ attr_reader :expires_at
29
+
30
+ # API client.
31
+ # определяем переменные
32
+ def initialize(auth_key = nil)
33
+ if auth_key.respond_to?(:auth_key) && auth_key.respond_to?(:params)
34
+ # auth_key is an OAuth2::Accessauth_key
35
+ @auth_key = auth_key.auth_key
36
+ @user_id = auth_key.params['user_id']
37
+ @expires_at = Time.at(auth_key.expires_at) unless auth_key.expires_at.nil?
38
+ else
39
+ # если auth_key нет или пришла строка (string)
40
+ @auth_key = auth_key
41
+ end
42
+ end
43
+
44
+ # Авторизирован пользователь.
45
+ def authorized?
46
+ !@auth_key.nil?
47
+ end
48
+
49
+ # Просрочет ключь или нет.
50
+ def expired?
51
+ @expires_at && @expires_at < Time.now
52
+ end
53
+
54
+
55
+ # Права доступа для auth_key.
56
+ # @return Symbol
57
+ def scope
58
+
59
+ SCOPE.reject do |access_scope, mask|
60
+ return SCOPE.invert[settings]
61
+ end
62
+
63
+ end
64
+
65
+ # Если вызываемы метод содержется в namespace, создается новый `VkontakteApi::Namespace` инстанс.
66
+ # `VkontakteApi::Namespace` так же выхывает method_missing для метода объекта Namespace
67
+ # если нет namspace `VkontakteApi::Method` создаеся объект API в который передаются параметры.
68
+ def method_missing(*args, &block)
69
+ if Namespace.exists?(args.first)
70
+ create_namespace(args.first)
71
+ else
72
+ call_method(args, &block)
73
+ end
74
+ end
75
+
76
+ private
77
+ def settings
78
+ @settings ||= @auth_key[0].gsub(/[^0-9]/,'4').to_i
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,29 @@
1
+ module ToNetMeApi
2
+ # Генерация модуля конфигураци
3
+ #
4
+ # ToNetMeApi::Configuration
5
+ module Configuration
6
+ #доступные опции для конфигурации
7
+ OPTION_NAMES = [
8
+ :api_core,
9
+ ]
10
+
11
+ attr_accessor *OPTION_NAMES
12
+
13
+ # адрес api по умолчанию
14
+ DAFAULT_API_ADDRESS = 'http://api.2net.me/'
15
+
16
+ # Можно задавать конфигурацию для гема так:
17
+ # ToNetMeApi.configure {|config| config.api_core='http://sandbox.api.2net.me/'}
18
+
19
+ def configure
20
+ yield self if block_given?
21
+ self
22
+ end
23
+
24
+ #установка всех конфигураций в дефолтное значение
25
+ def reset
26
+ @api_core = DAFAULT_API_ADDRESS
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,54 @@
1
+ module ToNetMeApi
2
+ # An exception raised by `ToNetMeApi::Result` when given a response with an error.
3
+ class Error < StandardError
4
+ # An error code.
5
+ # @return [Fixnum]
6
+ attr_reader :error_code
7
+ # Captcha identifier (only for "Captcha needed" errors).
8
+ # @return [String]
9
+ attr_reader :captcha_sid
10
+ # Captcha image URL (only for "Captcha needed" errors).
11
+ # @return [String]
12
+ attr_reader :captcha_img
13
+
14
+ # An exception is initialized by the data from response mash.
15
+ # @param [Hash] data Error data.
16
+ def initialize(data)
17
+ @error_code = data.error_code
18
+ @error_msg = data.error_msg
19
+
20
+ request_params = parse_params(data.request_params)
21
+
22
+ @method_name = request_params.delete('method')
23
+ @access_token = request_params.delete('access_token')
24
+ @oauth = request_params.delete('oauth')
25
+ @params = request_params
26
+
27
+ @captcha_sid = data.captcha_sid
28
+ @captcha_img = data.captcha_img
29
+ end
30
+
31
+ # A full description of the error.
32
+ # @return [String]
33
+ def message
34
+ message = "VKontakte returned an error #{@error_code}: '#{@error_msg}'"
35
+ message << " after calling method '#{@method_name}'"
36
+
37
+ if @params.empty?
38
+ message << " without parameters."
39
+ else
40
+ message << " with parameters #{@params.inspect}."
41
+ end
42
+
43
+ message
44
+ end
45
+
46
+ private
47
+ def parse_params(params)
48
+ params.inject({}) do |memo, pair|
49
+ memo[pair[:key]] = pair[:value]
50
+ memo
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,45 @@
1
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/api'
2
+ # require '~/rubystack/projects/users_part/lib/to_net_me_api/result'
3
+ module ToNetMeApi
4
+ # An API method. It is responsible for generating it's full name and determining it's type.
5
+ class Method
6
+ include Resolvable
7
+
8
+ # A pattern for names of methods with a boolean result.
9
+ PREDICATE_NAMES = /^is.*\?$/
10
+
11
+ # Calling the API method.
12
+ # It delegates the network request to `API.call` and result processing to `Result.process`.
13
+ # @param [Hash] args Arguments for the API method.
14
+ def call(args = {}, &block)
15
+ # raise full_name.inspect
16
+ response = API.call(full_name, args, auth_key)
17
+ # raise type.inspect
18
+ # когда ответ бует стандартизирован тогда нужно будет делать вывод результата иобработку ошибок
19
+ # Result.process(response, type, block)
20
+ end
21
+
22
+ private
23
+ def full_name
24
+ parts = [@previous_resolver.name, @name].compact.map { |part| camelize(part) }
25
+ parts.join(' ').gsub(/[^A-Za-z.]/, '/')
26
+ end
27
+
28
+ def type
29
+ @name =~ PREDICATE_NAMES ? :boolean : :anything
30
+ end
31
+
32
+ # camelize('get_profiles')
33
+ # => 'getProfiles'
34
+ def camelize(name)
35
+ words = name.split('_')
36
+ first_word = words.shift
37
+
38
+ words.each do |word|
39
+ word.sub!(/^[a-z]/, &:upcase)
40
+ end
41
+
42
+ words.unshift(first_word).join
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,43 @@
1
+ require '~/rubystack/projects/users_part/lib/to_net_me_api/resolvable'
2
+ require '~/rubystack/projects/users_part/lib/to_net_me_api/resolver'
3
+ require 'yaml'
4
+
5
+ module ToNetMeApi
6
+ # API метод namespace (такие как `users` или `search`).
7
+ #
8
+ # Включает в себя два модуля `Resolvable` и `Resolver`
9
+ # которые вызывают методы api с помощью `Resolver#call_method`.
10
+ # также класс содержит список всех объектов api.2net.me.
11
+ class Namespace
12
+ include Resolvable
13
+ include Resolver
14
+
15
+ # создает и вызывает `ToNetMeApi::Method` используя `ToNetMeApi::Resolver#call_method`.
16
+ def method_missing(*args, &block)
17
+
18
+ call_method(args, &block)
19
+
20
+ end
21
+
22
+ class << self
23
+ # Массив всех объектов api.2net.me.
24
+ #
25
+ # Загрузка файла `namespaces.yml` .
26
+ # @return [Array] An array of strings
27
+ def names
28
+ if @names.nil?
29
+ filename = File.expand_path('../namespaces.yml', __FILE__)
30
+ @names = YAML.load_file(filename)
31
+ end
32
+
33
+ @names
34
+ end
35
+
36
+ # Проверяет есть ли такой объект у api.2net.me?
37
+ # @param [String, Symbol] name
38
+ def exists?(name)
39
+ names.include?(name.to_s)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,7 @@
1
+ - audios
2
+ - groups
3
+ - posts
4
+ - search
5
+ - users
6
+ - index
7
+ - help
@@ -0,0 +1,20 @@
1
+ module ToNetMeApi
2
+
3
+ module Resolvable
4
+ attr_reader :name
5
+
6
+ # инициализация объекта и метода api.2net.me
7
+ # @param [String] name The name of this resolvable.
8
+ # @option options [Hashie::Mash] :resolver A mash holding information about the previous resolver.
9
+ def initialize(name, options = {})
10
+ @name = name.to_s
11
+ @previous_resolver = options.delete(:resolver)
12
+ end
13
+
14
+ # Returns the auth_key from the previous resolver.
15
+ # @return [String] A auth_key.
16
+ def auth_key
17
+ @previous_resolver.auth_key
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,34 @@
1
+ # require 'hashie'
2
+ module ToNetMeApi
3
+ # A mixin for classes that will resolve other classes' objects via `#method_missing`.
4
+ module Resolver
5
+ # A `Hashie::Mash` structure holding the name and auth_key of current instance.
6
+ # @return [Hashie::Mash]
7
+ def resolver
8
+ @resolver ||= Hashie::Mash.new(name: @name, auth_key: auth_key)
9
+ end
10
+
11
+ private
12
+ def create_namespace(name)
13
+ Namespace.new(name, resolver: resolver)
14
+ end
15
+
16
+ def create_method(name)
17
+ Method.new(name, resolver: resolver)
18
+ end
19
+
20
+ def call_method(args, &block)
21
+ create_method(args.shift).call(args.first || {}, &block)
22
+ end
23
+
24
+ # class << self
25
+ # # When this module is included, it undefines the `:send` instance method in the `base_class`
26
+ # # so it can be resolved via `method_missing`.
27
+ # def included(base_class)
28
+ # base_class.class_eval do
29
+ # undef_method :send
30
+ # end
31
+ # end
32
+ # end
33
+ end
34
+ end
@@ -0,0 +1,49 @@
1
+ module ToNetMeApi
2
+ # A module that handles method result processing.
3
+ #
4
+ # It implements method blocks support, result typecasting and raises `ToNetMeApi::Error` in case of an error response.
5
+ module Result
6
+ class << self
7
+ # The main method result processing.
8
+ # @param [Hashie::Mash] response The server response in mash format.
9
+ # @param [Symbol] type The expected result type (`:boolean` or `:anything`).
10
+ # @param [Proc] block A block passed to the API method.
11
+ # @return [Array, Hashie::Mash] The processed result.
12
+ # @raise [ToNetMeApi::Error] raised when VKontakte returns an error response.
13
+ def process(response, type, block)
14
+ raise response['error_code'].inspect
15
+ result = extract_result(response)
16
+
17
+ if result.respond_to?(:each)
18
+ # enumerable result receives :map with a block when called with a block
19
+ # or is returned untouched otherwise
20
+ block.nil? ? result : result.map(&block)
21
+ else
22
+ # non-enumerable result is typecasted
23
+ # (and yielded if block_given?)
24
+ result = typecast(result, type)
25
+ block.nil? ? result : block.call(result)
26
+ end
27
+ end
28
+
29
+ private
30
+ def extract_result(response)
31
+ if response.error?
32
+ raise ToNetMeApi::Error.new(response.error)
33
+ else
34
+ response.response
35
+ end
36
+ end
37
+
38
+ def typecast(parameter, type)
39
+ case type
40
+ when :boolean
41
+ # '1' becomes true, '0' becomes false
42
+ !parameter.to_i.zero?
43
+ else
44
+ parameter
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,4 @@
1
+ module ToNetMeApi
2
+ # Library version.
3
+ VERSION = '0.2'
4
+ end
@@ -0,0 +1,25 @@
1
+ # encoding: utf-8
2
+ $: << File.expand_path('../lib', __FILE__)
3
+ require 'to_net_me_api/version'
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = 'to_net_me_api'
7
+ s.version = ToNetMeApi::VERSION
8
+ s.authors = ['Sergey Chechaev']
9
+ s.email = ['sergey@2net.me']
10
+ s.homepage = 'https://github.com/sergey-chechaev/to_net_me_api'
11
+ s.summary = %q{Ruby wrapper for api.2net.me}
12
+ s.description = %q{A transparent wrapper for 2net.me API. Supports ruby-way naming of API methods (without method lists inside) with api request by HTTParty.}
13
+ s.license = ''
14
+
15
+ s.files = `git ls-files`.split("\n")
16
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
+ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
18
+ s.require_paths = ['lib']
19
+
20
+ s.required_ruby_version = '>= 1.9.3'
21
+
22
+ s.add_runtime_dependency 'httparty', '~> 0.11'
23
+ s.add_runtime_dependency 'hashie', '~> 2.0'
24
+
25
+ end
metadata CHANGED
@@ -1,15 +1,15 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: to_net_me_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.beta
5
- prerelease: 4
4
+ version: '0.2'
5
+ prerelease:
6
6
  platform: ruby
7
7
  authors:
8
8
  - Sergey Chechaev
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2013-09-25 00:00:00.000000000 Z
12
+ date: 2013-09-26 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: httparty
@@ -52,7 +52,21 @@ extensions: []
52
52
  extra_rdoc_files: []
53
53
  files:
54
54
  - .gitignore
55
+ - CHANGELOG.md
55
56
  - README.md
57
+ - lib/to_net_me_api.rb
58
+ - lib/to_net_me_api/api.rb
59
+ - lib/to_net_me_api/client.rb
60
+ - lib/to_net_me_api/configuration.rb
61
+ - lib/to_net_me_api/error.rb
62
+ - lib/to_net_me_api/method.rb
63
+ - lib/to_net_me_api/namespace.rb
64
+ - lib/to_net_me_api/namespaces.yml
65
+ - lib/to_net_me_api/resolvable.rb
66
+ - lib/to_net_me_api/resolver.rb
67
+ - lib/to_net_me_api/result.rb
68
+ - lib/to_net_me_api/version.rb
69
+ - to_net_me_api.gemspec
56
70
  homepage: https://github.com/sergey-chechaev/to_net_me_api
57
71
  licenses:
58
72
  - ''
@@ -69,9 +83,9 @@ required_ruby_version: !ruby/object:Gem::Requirement
69
83
  required_rubygems_version: !ruby/object:Gem::Requirement
70
84
  none: false
71
85
  requirements:
72
- - - ! '>'
86
+ - - ! '>='
73
87
  - !ruby/object:Gem::Version
74
- version: 1.3.1
88
+ version: '0'
75
89
  requirements: []
76
90
  rubyforge_project:
77
91
  rubygems_version: 1.8.24