每天一剂Rails良药之Syndicate Your Site With RSS

今天来看看Rails对RSS的支持:
feed_controller.rb:
class FeedController < ApplicationController
  session \:off

  def recipes
    @recipes = Recipe.find(:all,
                           \:order => "updated_at, created_at",
                           :limit => 15)
    @headers["Content-Type"] = "application/rss+xml"
  end
end

因为RSS请求是无状态的,所以session \:off可以提高性能
recipes.rxml:
xml.instruct!
xml.rss "version" => "2.0"
        "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
  xml.channel do
    xml.title 'Recipes on Rails'
    xml.link url_for(\:only_path => false,
                     :controller => 'recipes',
                     :action => 'list')
    xml.pubDate CGI.rfc1123_date(@recipes.first.updated_at)
    xml.description h("Recipes created for and by guys who shouldn't be cooking.")
    @recipes.each do |recipe|
      xml.item do
        xml.title recipe.title
        xml.link url_for(\:only_path => false,
                         :controller => 'recipes',
                         :id => recipe)

        xml.description h(recipe.instructions.to_s)
        xml.pubDate CGI.rfc1123_date(recipe.updated_at)
        xml.guid url_for(\:only_path => false,
                         :controller => 'recipes',
                         :action => 'show',
                         :id => recipe)
        xml.author h(recipe.author.name)
      end
    end
  end
end

这样生成的RSS feed的例子为:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Recipes on Rails</title>
    <link>http://myserver:2007/recipes/list</link>
    <pubDate>Fri, 03 Mar 2007 04:53:50 GMT</pubDate>
    <description>
      Recipes created for and by guys who shouldn't be cooking.
    </description>
    <item>
      <title>Canned Fish and Chips</title>
      <link>http://myserver:2007/recipes/show/6</link>
      <description>
        1. Open can. 2. Empty contents into bowl. 3. Serve.
      </description>
      <pubDate>Fri, 03 Mar 2007 04:58:42 GMT</pubDate>
      <guid>http://:2003/recipes/show/6</guid>
      <author>David</author>
    </item>
  </channel>
</rss>

另外我们可以在网站首页的<head>标签里加上以下内容以便于RSS订阅工具自动找到本网站的RSS:
<%= auto_discovery_link_tag(:rss,
                            {:controller => 'feed', :action => 'recipes'}) %>

这段代码将为我们生成<link>标签,如:
<link href="http://www.chadfowler.com/index.cgi?rss"
      rel="alternate"
      title="RSS"
      type="application/rss+xml" />


BTW:蛙眼把文章中的“: o”用笑脸图片来替换,真是很弱智好不好。

你可能感兴趣的:(xml,cgi,Rails)