controller
1 2 3 4 5 6 7 8 9 10 11
feed = RssParser.run("http://ws.audioscrobbler.com/1.0/user/me/recenttracks.rss") song1 = feed[:items][0][:title] song2 = feed[:items][1][:title] song3 = feed[:items][2][:title] @songs = [song1, song2, song3] feed = RssParser.run("http://ws.audioscrobbler.com/1.0/user/me/recenttracks.rss") link1 = feed[:items][0][:link] link2 = feed[:items][1][:link] link3 = feed[:items][2][:link] @links = [link1, link2, link3]
view
1 2 3 4 5 6
<ul id="lastfm_update_list"> <% @songs.each do |song, count| count=0 %> <li><%= link_to song, @links[count] %></li> <% count+1 %> <% end %> </ul>
Refactorings
No refactoring yet !
Elij
September 6, 2008, September 06, 2008 20:18, permalink
1 2 3 4 5 6 7 8 9
@songs = {} feed = RssParser.run("http://ws.audioscrobbler.com/1.0/user/me/recenttracks.rss") feed[:items].each { |item| @songs[item[:title]] = item[:link] } <ul id="lastfm_update_list"> <% @songs.each do |title, link| %> <li><%= link_to title, link %></li> <% end %> </ul>
Jason Dew
September 6, 2008, September 06, 2008 20:21, permalink
How about this?
helper
1 2 3 4 5
def extract source, number, attribute (0..(number-1)).inject(Array.new) do |result, index| result << source[index][attribute] end end
controller
1 2 3
feed = RssParser.run("http://ws.audioscrobbler.com/1.0/user/me/recenttracks.rss") @songs = extract feed[:items], 3, :title @links = extract feed[:items], 3, :link
view
1 2 3 4 5
<ul id="lastfm_update_list"> <% @songs.each_with_index do |song, count| %> <li><%= link_to song, @links[count] %></li> <% end %> </ul>
danielharan
September 6, 2008, September 06, 2008 20:31, permalink
What Elij wrote. It avoids 2 calls to RssParser.run (which could be making 2 HTTP calls, slowing your program down).
1 2 3 4 5 6 7 8 9 10
# For the initial view, there's a better way to keep track of 'count' # each_with_index is in Enumerable <ul id="lastfm_update_list"> <% @songs.each_with_index do |song, index| %> <li><%= link_to song, @links[index] %></li> <% end %> </ul> # only extract the first 3 items with [0..2] feed[:items][0..2].each do { |item| @songs[item[:title]] = item[:link] }
Im new to Ruby, I think it shows.
Any help much appreciated, thanks!