Class: MicroVkontakte::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/micro_vkontakte/session.rb

Constant Summary collapse

VK_METHODS =
%w{
  wall friends photos messages newsfeed status audio video places 
  secure language notes pages offers questions polls subscriptions
}
VK_API_URL =
'http://api.vk.com/api.php'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id, api_secret, prefix = nil) ⇒ Session

Returns a new instance of Session.



16
17
18
# File 'lib/micro_vkontakte/session.rb', line 16

def initialize(app_id, api_secret, prefix = nil)
  @app_id, @api_secret, @prefix = app_id, api_secret, prefix
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



39
40
41
# File 'lib/micro_vkontakte/session.rb', line 39

def method_missing(name, *args)
  call(name, *args)
end

Instance Attribute Details

#api_secretObject

Returns the value of attribute api_secret.



14
15
16
# File 'lib/micro_vkontakte/session.rb', line 14

def api_secret
  @api_secret
end

#app_idObject

Returns the value of attribute app_id.



14
15
16
# File 'lib/micro_vkontakte/session.rb', line 14

def app_id
  @app_id
end

Class Method Details

.add_method(method) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/micro_vkontakte/session.rb', line 44

def add_method(method)
  self.class_eval do
    define_method(method) do
      variable = instance_variable_get("@#{method}")
      unless variable
        variable = self.class.new(app_id, api_secret, method)
        instance_variable_set("@#{method}", variable)
      end
      variable
    end
  end
end

Instance Method Details

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



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/micro_vkontakte/session.rb', line 20

def call(method, params = {})
  params[:method] = @prefix ? "#{@prefix}.#{method}" : method
  params[:api_id] = app_id
  params[:format] = 'json'
  params[:v] = '3.0'
  params[:sig] = sig(params.stringify_keys)
  response = JSON.parse(Net::HTTP.post_form(URI.parse(VK_API_URL), params).body)
  if response['error']
    raise ServerError.new(params[:method], params, response['error'])
  end
  response['response']
end

#sig(params) ⇒ Object



33
34
35
36
37
# File 'lib/micro_vkontakte/session.rb', line 33

def sig(params)
  Digest::MD5::hexdigest(
    params.keys.sort.map{|key| "#{key}=#{params[key]}"}.join + api_secret
  )
end