Class: Scrobbler::REST::Connection

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

Instance Method Summary (collapse)

Constructor Details

- (Connection) initialize(base_url, args = {})

Returns a new instance of Connection



6
7
8
9
10
# File 'lib/scrobbler/rest.rb', line 6

def initialize(base_url, args = {})
	@base_url = base_url
	@username = args[:username]
	@password = args[:password]
end

Instance Method Details

- (Object) get(resource, args = nil)



12
13
14
# File 'lib/scrobbler/rest.rb', line 12

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

- (Object) post(resource, args = nil)



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

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

- (Object) request(resource, method = "get", args = nil)



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/scrobbler/rest.rb', line 20

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

	if args
		url.query = args.map { |k,v| "%s=%s" % [escape(k.to_s), escape(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) }
	res.body
end