August 9, 2007

Now You Can Add RSS Feeds To A Rails Site

RSS logoWe've recently added some RSS feeds to make it easier to keep track of changes made to the ProductCritic site. This is an easy feature to add extra value to your site and with Rails it's quite easy.

There a number of ways to do this but I decided to use a straight forward method of using an XML view.

First step is to create a new method in your controller. For the home page feed which provides updates on the latest product reviews on the site, I added an 'rss' method to the PageController class that looked something like this:
def rss
@products = Product.find(:all, :order => 'created_at desc', :limit => 20)
render :layout => false
end
Now all that is needed is to create a 'app/views/page/rss.rxml' file to create the RSS feed. In this example I used this:
xml.instruct! :xml, :version => '1.0', :encoding => 'utf-8'
xml.rss('version' => '2.0') do
xml.channel do
xml.title "Latest Products from ProductCritic"
xml.link(request.protocol + request.host_with_port + home_path)
xml.description("Recently added products to ProductCritic.")
xml.language "en"
xml.ttl "40"
xml.pubDate(Time.now.rfc822)
@products.each do |p|
xml.item do
url = request.protocol + request.host_with_port +
url_for(:controller => 'product', :action => 'show', :id => p)
xml.title("#{h(p.name)} (#{p.score})")
xml.description(h(truncate(p.teaser, 500)))
xml.link(url)
xml.guid(url)
end
end
end
end
Ruby and Rails both have some nice helper methods to make creating the feed. Ruby's Time class has a rfc822 method which correctly generates a date-time in the required format and Rails has a truncate method to keep the body of the post a reasonable length.

With this method, we've added feeds for:
  1. The main site - provides updates on the latest products added to ProductCritic
  2. Digital Camera Reviews - provides updates on the latest cameras added to the site
  3. Camcorder Reviews - provides updates on the latest camcorders added to the site
  4. Cell Phone Reviews - provides updates on the latest cell phones added to the site
Finally, we added a feed for every product that is on ProductCritic. This means that if you are interested in one specific product (e.g. the iPhone), you can get a RSS feed for it and get updates whenever we add a new review specifically for that product you're interested in.

If you have requests for any other feeds from the site send us some feedback and we'll see what we can do.

Labels: , ,

0 Comments:

Post a Comment

<< Home