Read my latest article: 8 things I look for in a Ruby on Rails app (posted Thu, 06 Jul 2017 16:59:00 GMT)

Parsing a RSS Feed

Posted by Wed, 11 May 2005 20:44:00 GMT

2 comments Latest by Neil Chandler Thu, 04 Feb 2010 09: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 &lt; 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.

Get help with your Rails project

comments powered by Disqus
Comments
  1. Avatar
    blah Sat, 03 Jun 2006 22:45:43 GMT

    blah blah blah. wanna buy some erection cream?

  2. Avatar
    Neil Chandler Thu, 04 Feb 2010 09:43:09 GMT

    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