首先,现在我建议使用 ATOM feed 而不是 RSS.
ATOM feed 的规范在国际化、内容类型等方面比 RSS 提供更多价值and每个现代提要阅读器都支持它。
有关 ATOM 与 RSS 的更多信息可以在以下位置找到:
- the 维基百科 ATOM 条目 http://en.wikipedia.org/wiki/Atom_(standard)#Atom_compared_to_RSS_2.0
-
专业博主 http://www.problogger.net/archives/2006/03/30/rss-vs-atom-whats-the-big-deal/ and 自由营销区 http://www.freemarketingzone.com/rss/atom-vs-rss.html关于该主题的博客文章
继续编码:
此示例假设:
- 一个名为
NewsItem
具有以下属性:
title
content
author_name
- 该模型的控制器(
news_items_controller.rb
),您将在其中添加feed
action
我们将为此使用构建器模板和 Ruby on Railsatom_feed 助手 http://api.rubyonrails.org/classes/ActionView/Helpers/AtomFeedHelper.html这是很有用的。
1. 将动作添加到控制器中
Go to app/controllers/news_items_controller.rb
并添加:
def feed
# this will be the name of the feed displayed on the feed reader
@title = "FEED title"
# the news items
@news_items = NewsItem.order("updated_at desc")
# this will be our Feed's update timestamp
@updated = @news_items.first.updated_at unless @news_items.empty?
respond_to do |format|
format.atom { render :layout => false }
# we want the RSS feed to redirect permanently to the ATOM feed
format.rss { redirect_to feed_path(:format => :atom), :status => :moved_permanently }
end
end
2. 设置您的构建器模板
现在让我们添加模板来构建提要。
Go to app/views/news_items/feed.atom.builder
并添加:
atom_feed :language => 'en-US' do |feed|
feed.title @title
feed.updated @updated
@news_items.each do |item|
next if item.updated_at.blank?
feed.entry( item ) do |entry|
entry.url news_item_url(item)
entry.title item.title
entry.content item.content, :type => 'html'
# the strftime is needed to work with Google Reader.
entry.updated(item.updated_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
entry.author do |author|
author.name entry.author_name
end
end
end
end
3. 将其与路线连接起来
让我们在以下位置提供提要:http://domain.example/feed
这将默认调用 ATOM 格式的操作并重定向/feed.rss
to /feed.atom
.
Go to config/routes.rb
并添加:
resources :news_items
match '/feed' => 'news_items#feed',
:as => :feed,
:defaults => { :format => 'atom' }
4. 在布局上添加 ATOM 和 RSS feed 的链接
最后,剩下的就是将提要添加到布局中。
Go to app/views/layouts/application.html.erb
并将其添加到您的<head></head>
部分:
<%= auto_discovery_link_tag :atom, "/feed" %>
<%= auto_discovery_link_tag :rss, "/feed.rss" %>