Now You Can Add RSS Feeds To A Rails Site
We'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 rssNow 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:
@products = Product.find(:all, :order => 'created_at desc', :limit => 20)
render :layout => false
end
xml.instruct! :xml, :version => '1.0', :encoding => 'utf-8'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.
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
With this method, we've added feeds for:
- The main site - provides updates on the latest products added to ProductCritic
- Digital Camera Reviews - provides updates on the latest cameras added to the site
- Camcorder Reviews - provides updates on the latest camcorders added to the site
- Cell Phone Reviews - provides updates on the latest cell phones added to the site
If you have requests for any other feeds from the site send us some feedback and we'll see what we can do.





