Class: REST::Connection

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

Instance Method Summary collapse

Constructor Details

#initialize(base_url, options = {}) ⇒ Connection

Returns a new instance of Connection.



8
9
10
11
12
13
14
15
# File 'lib/rest.rb', line 8

def initialize(base_url, options = {})
	@base_url = base_url
	@username = options[:username]
	@password = options[:password]
	
	@rate_limit   = options[:rate_limit].to_f
	@lock_expiry  = Time.now.to_f
end

Instance Method Details

#get(resource, args = nil) ⇒ Object



17
18
19
# File 'lib/rest.rb', line 17

def get(resource, args = nil)
	request(resource, "get", args)
end

#post(resource, args = nil) ⇒ Object



21
22
23
# File 'lib/rest.rb', line 21

def post(resource, args = nil)
	request(resource, "post", args)
end

#request(resource, method = "get", args = {}) ⇒ Object



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
# File 'lib/rest.rb', line 25

def request(resource, method = "get", args = {})
	url = URI.join(@base_url, resource)

	unless args.empty?
		# TODO: What about keys without value?
		url.query = args.map { |k,v| "%s=%s" % [URI.encode(k.to_s), URI.encode(v.to_s)] }.join("&")
	end
				
	case method
	when "get"
		req = Net::HTTP::Get.new(url.request_uri)
	when "post"
		req = Net::HTTP::Post.new(url.request_uri)
	end

	if @username and @password
		req.basic_auth(@username, @password)
	end

	http = Net::HTTP.new(url.host, url.port)
	http.use_ssl = (url.port == 443)

	res = http.start() { |conn| conn.request(req) }
	puts url
	res.body
end

#request_with_rate_limiting(*args) ⇒ Object



52
53
54
55
56
# File 'lib/rest.rb', line 52

def request_with_rate_limiting(*args)
  sleep @lock_expiry - Time.now.to_f rescue ArgumentError
  @lock_expiry = Time.now.to_f + @rate_limit
  request_without_rate_limiting(*args)
end