Class: Mostscrobbled::LastFm::Connection

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

Constant Summary collapse

REQUIRED_ATTRIBUTES =
:username, :api_key

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Connection

Returns a new instance of Connection.

Raises:



15
16
17
18
# File 'lib/mostscrobbled/last_fm.rb', line 15

def initialize(opts = {})
	raise ConfigError, missing_options(opts).map{ |argument| ":#{argument} argument missing" }.join(" and ") unless missing_options(opts).empty?
	opts.keys.each{ |key| send("#{key}=", opts[key]) }
end

Instance Method Details

#artistsObject

Returns an array of MostscrobbledArtist objects



21
22
23
24
25
26
27
28
29
# File 'lib/mostscrobbled/last_fm.rb', line 21

def artists
	(artists = []).tap do 
		total_artist_pages.times do |page|
			artists_xml(page).xpath('//artist').collect do |node|
				artists << Mostscrobbled::Artist.build_artist(node)
			end
		end
	end
end

#artists_uri(page_number = nil) ⇒ Object



31
32
33
# File 'lib/mostscrobbled/last_fm.rb', line 31

def artists_uri(page_number = nil)
	URI.parse("http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=#{api_key}&user=#{username}#{"&page=#{page_number + 1}" if page_number}")
end

#artists_xml(page_number = nil) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mostscrobbled/last_fm.rb', line 35

def artists_xml(page_number = nil)
	uri = artists_uri(page_number)
	http = Net::HTTP.new(uri.host)
	request = Net::HTTP::Get.new(uri.request_uri)
	response = http.request(request)
	case response.code
	when "200"
		@artists_xml ||= {}
		@artists_xml[page_number || 0] ||= Nokogiri::XML(response.body)
	when "403"
		raise ResponseError, Nokogiri::XML(response.body).xpath(".//error").first.content.inspect
	end
end

#total_artist_pagesObject



49
50
51
# File 'lib/mostscrobbled/last_fm.rb', line 49

def total_artist_pages
	artists_xml.xpath('//artists').first["totalPages"].to_i
end