Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Created August 12, 2011 06:45
Show Gist options
  • Save timothyklim/1141588 to your computer and use it in GitHub Desktop.
Save timothyklim/1141588 to your computer and use it in GitHub Desktop.
vk_api.rb
#!/usr/bin/env ruby
# encode: utf-8
# Vkontakte api class
require 'digest/md5'
require 'json'
require 'rest_client'
class API
attr_reader :app_id, :app_secret
def initialize options = {}
@app_id = options[:app_id]
@app_secret = options[:app_secret]
end
def sig params
params.merge!({
api_id: @app_id,
format: 'json',
rnd: rand(1000),
timestamp: Time.now.to_i,
v: '3.0',
})
_sig = Digest::MD5.hexdigest params.keys.sort.map { |key|
"#{key}=#{params[key]}"
}.join + @app_secret
params[:sig] = _sig
params
end
def method_missing method, *args, &block
response = JSON::parse(
RestClient.post(
'http://api.vk.com/api.php',
sig(args.first.merge method: method.to_s)
)
)
raise 'ServerError', response['error'] if response['error']
if block
yield response['response']
else
response['response']
end
end
end
# Example
api = API.new app_id: '222222222', app_secret: '722222222222'
api.getProfiles uids: (1..1000).to_a.join(','), fields: 'uid, first_name' do |req|
puts req.map { |item| item['uid'] }.join ', '
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment