Thursday, April 17, 2008

rss feed in rails

Note for the Way to create Atom and RSS 2.0 feed.

$ ./script/generate controller feed

Suppose that the model we want show in feed is Post

class FeedController < ApplicationController
    def rss
        @rss = @@post
    end

    def atom
        @atom = @@post
    end

  private
    @@post = Post.find :all,
        :order => "update_at", :limit => 10

end


Then write the view.

app/view/feed/rss.rxml

01 xml.instruct! :xml, :version=>"1.0"
02 xml.rss(:version=>"2.0"){
03     xml.channel{
04         xml.title("The site title")
05         xml.link(url_for("/"))
06         xml.description("The site description")
07         xml.language('en-us')
08
09         @rss.each do |rss|
10         xml.item {
11             xml.title rss.title
12             xml.link ""
13             xml.description rss.content
14             xml.pubDate rss.update_at
15             xml.guid ""
16             xml.author rss.declarer
17         }
18         end
19     }
20 }



app/view/feed/atom.rxml

01 xml.instruct! :xml, :version=>"1.0"
02 xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do
03     xml.title("The site title")
04     xml.link(url_for "/")
05     @atom.each do |atom|
06         xml.entry {
07             xml.title(atom.title)
08             xml.summary(atom.content)
09         }
10     end
11 end


app/view/layout/application.rhtml add

<%= auto_discovery_link_tag :rss, { :controller => '/rss', :action => 'rss' }, { :title => "RSS 2.0" } %>
<%= auto_discovery_link_tag :rss, { :controller => '/rss', :action => 'atom' }, { :title => "Atom" } %>


 
 

No comments: