Blog

Rails3 RSS & ATOM Feed

Rails3 RSS & ATOM Feed

Today I created a RSS/Atom Feed for the blog of my Frick-Web page. I did following:

Requirements

I have a model called Blogpost with following relevant attributes:

  • name
  • content

Further a controller for this model is necessary. This controller handles the feed action (app/controllers/blogposts_controller.rb).

Step 1:

Add following action in your controller (app/controllers/blogposts_controller.rb):

def feed
  @title = "Your feed title (e.g. Matthias Frick - Blog - Feed)"
 
  # all blogposts
  @blogposts = Blogpost.order("created_at desc")
 
  # update timestamp for the feed
  @updated = @blogposts.first.updated_at unless @blogposts.empty?
 
  respond_to do |format|
    format.atom { render :layout => false }
 
    # if you want to permanently redirect to the ATOM feed and do not use the RSS feed
    format.rss { redirect_to feed_path(:format => :atom), :status => :moved_permanently }
  end
end

Step 2:

You have to add a template for building your feed:

Add following template in your views (app/views/blogposts/feed.atom.builder):

atom_feed :language => 'en-US' do |feed|
  feed.title @title
  feed.updated @updated	
  
  @blogposts.each do |blogpost|
    next if blogpost.updated_at.blank?
    
    feed.entry(blogpost) do |entry|
      entry.url blogpost_url(blogpost)
      entry.title blogpost.name
      entry.content blogpost.content, :type => 'html'
      entry.updated(blogpost.updated_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
	
      entry.author do |author|
        author.name("Your Author") # could be in your DB, or just static
      end
    end
  end
end

Step 3:

Now the feed must be available through an URL like http://www.frick-web.at/feed.

Add following to your routes (config/routes.rb):

match "/feed" => "blogposts#feed", :as => :feed, :defaults => { :format => "atom" }

 

Step 4:

In the last step you have to add the feed to your layout:

Add following to your layout (app/views/layouts/application.html.erb). You have to add it in the <head></head> section:

<%= auto_discovery_link_tag :atom, "/feed" %>
<%= auto_discovery_link_tag :rss, "/feed.rss" %>

 

That´s it. The feed is ready.

09.08.2011
Matthias Frick
Ruby on Rails
0 Kommentare

Über den Autor

Matthias Frick
Matthias Frick, MSc.

Er ist ein langjähriger Ruby-on-Rails Entwickler und leitet das Unternehmen Frick-Web.

0 Kommentare zu "Rails3 RSS & ATOM Feed"

Kommentar verfassen