Building a RSS feed in Ruby on Rails is very easy, it feels like almost built in. We'll use the XML Builder handler that comes with Rails, so let's get started.
Let's assume we want to add the feed to our company blog, made of Article
models. Each article has a title and a body property. The ArticlesController
is a normal CRUD Rails controller; we'll add the feed to the index
action, so let's update that now:
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.last(10)
respond_to do |format|
format.html
format.rss { render :layout => false }
end
end
end
The code above just removes the layout from RSS view, which will create next:
# app/views/articles/index.rss.builder
xml.instruct! :xml, :version => "1.0"
xml.rss :version => "2.0" do
xml.channel do
xml.title "My Company Blog"
xml.description "This is a blog by My Company"
xml.link root_url
@articles.each do |article|
xml.item do
xml.title article.title
xml.description article.body
xml.pubDate article.published_at.to_s(:rfc822)
xml.link article_url(article)
xml.guid article_url(article)
end
end
end
end
Adding the code inside a index.rss.builder
file instructs Rails to use Builder Rails handler to handle it and rss as format.
The file creates a RSS 2 file, but we don't use all the fields described in the specification. Notice how the publication date (pubDate
) is specified in the required RFC 822 format. Also it's best to show the full URLs to articles, rather than paths.
What's now left to do is add the feed link to the HEAD
of our HTML files, so let's add it to the layout file, inside <head>
tags:
<%= auto_discovery_link_tag :rss, articles_url(:format => :rss) %>
Rails provides auto_discovery_link_tag
to create a link tag for the browsers and feed readers. Now if we go to our /articles.rss
URL, we should see the feed of our latest 10 blog posts.
Happy coding!