movie rental service

Create A Simple RSS Reader With Ruby on Rails

September 4, 2007 – 3:51 am

I recently had to create a lightweight Ruby on Rails RSS Reader for the Notifir.com project, which we fund. I did not want to add any libraries for the best portability. Following is all the code you need to grab RSS feeds and display them on your site.

The following can go either in the controller or in a plugin:

class Reader
  def initialize(url)
    response = open(url).read
    @doc = REXML::Document.new(response)
  end

  def getFeeds()
    titles = []
    links = []
    titles_w_links = []
    @doc.elements.each("rss/channel/item/title") { |element|
      @titles << element.text
    }
    @doc.elements.each("rss/channel/item/link") { |element|
      @links << element.text
    }
  end
  count = 0
  @titles.each {|title|
    titles_w_links << "#{title}"
    count += 1
  }
  return titles_w_links
end

Then use this code in the view:

<%
require 'open-uri'
require 'rexml/document'
rss = RSSReader::Reader.new()
feeds = rss.getFeeds()
feeds.each { |feed|
%>
  <%=feed%>
<%
}
%>

  1. 3 Responses to “Create A Simple RSS Reader With Ruby on Rails”

  2. Ack… PHP on Rails

    By jc on Sep 5, 2007

  3. Umm, yea — PHP on rails for sure, wheres the handling here, where is the seperation. Not recommended.

    By Tobia on Sep 8, 2007

  4. Thanks for this code. After working with this I have decided that the best way for me to display rss feeds on my site is to actually use the rss tools at Fwicki.

    The syndication tools and the customizable reader provided by Fwicki works well for my purposes.

    But I do thank you for this code and the work you put into setting this post up.

    By George Stadler on Feb 15, 2008

Post a Comment