By requiring the ruby modules 'rss', 'open-uri' we can fetch, format and display track info from Last.fm. Last.fm does not provide a user's Top Weekly Tracks in RSS format, so we need to also require 'hpricot' and parse the XML. Below are some classes, which are called from a helper method. The helper methods run when the Sinatra route matches. After the route runs the helper method and the data has been stored in an instance variable, the view is rendered.
By requiring the ruby modules ‘rss’, ‘open-uri’ we can fetch, format and display track info from Last.fm.
Last.fm does not provide a user’s Top Weekly Tracks in RSS format, so we need to also require ‘hpricot’ and parse the XML.
Here are some classes I coded which are later called in a Sinatra helper and eventually the returned data is exposed in a view. You can see this in action here.
require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'rss'
class LastfmWeeklyTracksXML
def initialize(username)
@un = username
@url = "http://ws.audioscrobbler.com/2.0/user/#{@un}/weeklytrackchart.xml"
@data = []
end
# build an array of track info using xml data
def get_the_data
@doc = Hpricot.XML(open(@url))
(@doc/:track).each do |track|
t = { :artist => track.at("artist").innerHTML, :song => track.at("name").innerHTML, :url => "http://" + track.at("url").innerHTML,:plays => track.at("playcount").innerHTML}
@data.push(t)
end
return @data
end
end
class Feed
def initialize(url)
@url = url
@data = []
end
def read_feed
@document = open(@url).read
rss = RSS::Parser.parse(@document)
rss.items.each do |item|
@data.push({ :title => item.title, :url => item.link})
end
return @data
end
end
# call this from the route in app.rb
# either helpers or routes has to inherit the
# classes for getting Last.FM xml and rss data
def last_fm_info(datatype,username)
case datatype
when "loved"
url = "http://ws.audioscrobbler.com/2.0/user/#{username}/lovedtracks.rss"
f = Feed.new(url)
f.read_feed
when "recent"
url = "http://ws.audioscrobbler.com/1.0/user/#{username}/recenttracks.rss"
f = Feed.new(url)
f.read_feed
when "top-weekly"
url = "http://ws.audioscrobbler.com/2.0/user/#{username}/weeklytrackchart.xml"
f = LastfmWeeklyTracksXML.new(username)
f.get_the_data
end
end
# this code would be in your app.rb file
post '/demo/last-fm' do
datatype = params[:type]
username = params["lastfm-un"]
if datatype == "top-weekly"
@weekly = last_fm_info(datatype,username)
else
@tracks = last_fm_info(datatype,username)
end
@type = datatype.gsub("-"," ")
erb :lastfm
end
Content © Zach Hannes
Proudly powered by WordPress
Theme designed by Artisan Themes
28 queries.
0.454 seconds.