forked from eadz/rubyoverflow
/
rubyoverflow.rb
67 lines (56 loc) · 1.58 KB
/
rubyoverflow.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
path = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift(path) unless $LOAD_PATH.include?(path)
require 'httparty'
require 'ostruct'
require 'hashie'
require 'json'
require 'rubyoverflow/sites'
require 'rubyoverflow/users'
require "rubyoverflow/version"
module Rubyoverflow
class Client
include HTTParty
format :plain
HOST = 'http://api.stackoverflow.com'
VERSION = '1.1'
attr_accessor :host
attr_accessor :api_key
def initialize(options = OpenStruct.new)
if options.kind_of? OpenStruct
@host = options.host || HOST
@version = options.version || VERSION
@api_key = options.api_key if options.api_key
end
end
def request(path, parameters = {})
parameters['key'] = @api_key unless @api_key.nil? || @api_key.empty?
url = host_path + normalize(path) + query_string(parameters)
response = self.class.get url
return JSON.parse(response.body), url
end
def host_path
normalize(@host) + normalize(@version)
end
class << self
def stackauth_client(api_key = '')
options = OpenStruct.new
options.host = 'http://stackauth.com/'
options.api_key = api_key if api_key
Client.new options
end
end
private
def normalize(path)
path.end_with?('/') ? path : path+ '/'
end
def query_string(parameters)
if !parameters.empty?
params = parameters.sort_by { |k, v| k.to_s }
pairs = params.map { |key, value| "#{key}=#{value}" }
'?' + pairs.join('&')
else
''
end
end
end
end