displaying rss feeds in your rails app

4 May

Its very common to need to display recent news / posts from a blog outside of your Rails application. There are a few javascript widgets (like google reader) that make it easy to do that, but they suck from a performance standpoint. Its pretty easy to roll your own, here’s an example of how:

I got most of my info from http://rubyrss.com/

This is my home_helper.rb file

require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'

module HomeHelper
  
  def blog_feed
    source = "http://feeds.feedburner.com/37signals/beMH" # url or local file
    content = "" # raw content of rss feed will be loaded here
    open(source) do |s| content = s.read end
    rss = RSS::Parser.parse(content, false)
    
    html = "<ul>"
    rss.items.each do |i|
    html << "<li><a href='#{i.link}'>#{i.title}</a></li>"
    html << "</ul>"
    html
    
    end
  end
end

and then in my view I can just write

<%= blog_feed %>

You’ll see that it loops through all of the items in the feed by default, if you want to limit that you can use .first()

rss.items.first(3).each do |i|

This needs a little clean up and error handling but its gives you a basic idea how how to get a feed parsed and displayed on your site.

Advertisement

One Response to “displaying rss feeds in your rails app”

  1. Mike Rossetti August 27, 2011 at 9:18 pm #

    Awesome tutorial. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.