railsでrssフィードを作る

scaffoldで作成した一覧(index)用にrssフィードを作成してみた。
※モデル名はentry。

controller

controllerのrespond_toでハンドリング
rss2.0はindex.rxmlにリダイレクトさせる。

 def index
  #(略)
  respond_to do |format|
    format.atom    #atom用
    format.rss  { render(:action => "index.rxml") }    #rss2.0用

view

atomはviewにindex.atom.builderファイルを作成

atom_feed do |feed|
  feed.title("RssTitle")
  feed.updated((@entries.first.created_at))

  for entry in @entries
    feed.entry(entry) do |item|
      item.title(entry.title) 
      item.content(entry.content, :type => 'html')
      item.author do |author|
        author.name("RSSAuthor")
      end
    end
  end
end


rss2.0はindex.rxmlにリダイレクトさせるように記述。(上記参照:controller)
書き方は、こちらを参考にしました。
RailsでRSSフィードを配信するのは超簡単! - 医者を志す妻を応援する夫の日記
Rails 2.0 » Rails2.0によるAtom/RSSフィードの実装(GET)

xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8"
xml.rss('version' => '2.0', 'xmlns:atom' => 'http://www.w3.org/2005/Atom', 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearchrss/1.0/') do
  xml.channel do
    xml.title "Blog Title"
    xml.link(request.protocol + request.host_with_port + url_for(:rss => nil))
    xml.language "ja-ja"
    xml.ttl "40"
    xml.pubDate(Time.now.strftime("%a, %d %b %Y %H:%M:%S %Z"))
    @entries.each do |e|
      xml.item do
        xml.title(e.title)
        xml.link(request.protocol + request.host_with_port +
                 url_for(:controller => 'entries', :action => 'show', :id => e.id ))
        xml.description(e.content)
        xml.guid(request.protocol + request.host_with_port +
                 url_for(:controller => 'entries', :action => 'show', :id => e.id ))
        xml.pubDate(e.created_at)
        xml.author "RssAuthor"
      end
    end
  end
end

感想

atomの方が作るの簡単。でもrss2.0の方がmainstreamなんだろうか。