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.each{ |key,value| send("#{key}=", value) }
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

The uri used to call the last.fm api



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

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

The parsed XML returned from the last.fm api



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

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

The total number of pages returned by the last.fm api



52
53
54
# File 'lib/mostscrobbled/last_fm.rb', line 52

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