Seventh Octave

We're Starters. We write about culture, design and the business of software.

We believe software should be beautiful and inspired. Follow us as we build @TechOctave.

Create an RSS feed in Rails TVD Oct 15

Post a comment

Not too long ago, I showed you how to create a blog archive for your Rails blog. Well, creating an RSS feed for your Rails blog might not necessarily increase SEO like a Google Sitemap can, but it's a helluva great way to stay in touch with your readers.

Here's a walk through for integrating RSS with your Rails blog.

RSS and Ruby on Rails - The Full Story

app/controllers/posts_controller.rb

@posts = Post.all(:select => "title, author, id, content, posted_at", :order => "posted_at DESC", :limit => 20) 

respond_to do |format|
   format.rss { render :layout => false }
end

In Rails, this call sends all RSS calls to index.rss.builder by default. Let's take a look at what that View does.

app/views/posts/index.rss.builder

This is where all the Railsy magic happens. In another language, in another web application framework, this could've easily been ugly. But with Rails, we're talking rainbows and ponies baby!

xml.instruct! :xml, :version => "1.0" 
xml.rss :version => "2.0" do
  xml.channel do
    xml.title "Your Blog Title"
    xml.description "A blog about software and chocolate"
    xml.link posts_url

    for post in @posts
      xml.item do
        xml.title post.title
        xml.description post.content
        xml.pubDate post.posted_at.to_s(:rfc822)
        xml.link post_url(post)
        xml.guid post_url(post)
      end
    end
  end
end

You just implemented the RSS specification in Ruby on Rails. Congrats! Let's keep moving, we're almost done.

app/views/layouts/application.html.erb

You can get browsers to auto-detect your Rails blog rss feed with a single line of Ruby on Rails code:

<%= auto_discovery_link_tag(:rss, "http://iblog.com") %>

Or, if you want, you can use straight XHTML to get browsers to auto-detect your Rails blog rss feed:

<link href="http://iblog.com" rel="alternate" title="RSS" type="application/rss+xml" />

That's it, now mere mortals can subscribe to your feed and get inside the mind of a Rails master. Dramatic, I know!

Have fun and Good Luck!

If you enjoyed this post, subscribe for updates (it's free).

Email Address:

Comments are closed