Parsing a RSS Feed
23 comments Latest by Neil Chandler Thu, 04 Feb 2010 10:43:09 GMT
A friend was asking me how they could easily read a RSS feed and display the last x items in their rails project. This was my quick and dirty response.
require 'rss/2.0'
require 'open-uri'
class RssfeedController < ApplicationController
def index
feed_url = 'http://www.planetrubyonrails.org/xml/rss'
output = "<h1>My RSS Reader</h1>"
open(feed_url) do |http|
response = http.read
result = RSS::Parser.parse(response, false)
output += "Feed Title: #{result.channel.title}<br />"
result.items.each_with_index do |item, i|
output += "#{i+1}. #{item.title}<br />" if i < 10
end
end
render_text output
end
end
Is there an easier way to do this with another RSS library? I figured that the simplest method would be to just use the standard library that comes with Ruby.
Enjoying the content? Be sure to subscribe to my RSS feed.






blah blah blah. wanna buy some erection cream?
I found this googling for info on the simple-rss gem. Will try to write how I used it on http://ruby.vanhecke.info
Note: For this to work, you need to edit the last part of line 14. (It has an incorrectly encoded less-than sign between
if iand10.Here’s a version you can pop in you lib and call from your pages… cheers
Wow, I’ve been looking for this all day! Thank you!
i’m the type of guy that likes these kind of posts
thanks!
thanks!
thanks!
thanks!
Thanks Robby, really useful.
I refactored this to be more railsy:
In this case, the view (in haml) would be:
thanks for that quickie :)
Can I get a link for that erection cream?
how to parser RSS with Ajax on Rails?
Not to be grammatically picky, but one would say ‘an RSS feed’ as the pronunciation of letter R starts with a vowel sound.
Otherwise, a useful titbit, thanks :)
More than useful, small, dry, working. Thanks for that piece.
Cheers, Jason
The post is excellent, the comments make it even more usefull. Did you know you are nice guys ? :-)
Hi, this is very useful.
I will had to add some rescue statements for what I want to do, but this is a good start.
Thank you!
this can also be done with acts_as_feed http://github.com/grosser/acts_as_feed , which will represent the feed as feed model or as addition to a model, and parsing can be offloaded to a background process.
Just a quick update. The last line
posts[0..length – 1] if posts.size > length
will only return posts if the rss returns a number of posts > length otherwise it returns nil
posts.size > length ? posts[0..length – 1] : posts
should be used to return all posts when the total available posts is less the length