乐者为王

Do one thing, and do it well.

为Rails应用增加RSS输出功能

在EntriesController中增加feed方法,内容如下:

1
2
3
4
5
6
def feed
  @entries = Entry.all
  respond_to do |format|
    format.rss { render :layout => false }  # feed.rss.rxml
  end
end

在app/views/entries中增加feed.rss.rxml视图模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
xml.instruct! "xml", :version => "1.0"
xml.rss "version" => "2.0" do
  xml.channel do
    xml.title "example.com Entries"
    xml.description "Listing Entries for example.com"
    xml.link entries_url

    @entries.each do |entry|
      xml.item do
        xml.title entry.title
        xml.link entry_url(entry)
        xml.description entry.content
        xml.guid entry_url(entry)
      end
    end
  end
end

然后在config/routes.rb中添加:

1
map.feed '/feed', :controller => 'entries', :action => 'feed'

这样,当访问http://example.com/feed时就可看到所有内容的RSS输出了。

Comments