用户登录
用户注册

分享至

rails制作rss feed代码

  • 作者: 灯光没O耀眼
  • 来源: 51数据库
  • 2021-09-21
方法a:
就是你自己把rss xml的格式拼凑好,输出.并设置http header ,标记content-type为application/xml,常见的代码:
复制代码 代码如下:

#post_controller::feed()
def feed
require "rss"
articles = article.find :all, :order => 'post_date desc', :limit => 10
feed = rss::maker.make("2.0") do |maker|
maker.channel.title = "gang of technology"
maker.channel.description = "gang of technology site"
maker.channel.link = "http://www.51sjk.com/Upload/Articles/1/0/270/270345_20210708034332826.com"

maker.items.do_sort = true

articles.each do |article|
item = maker.items.new_item
item.link = "http://www.***.com/archives/#{article.id}"
item.title = article.title
item.date = article.post_date
item.description = ""
end
end
send_data feed.to_s, :type => "application/rss+xml", :disposition =>
'inline'
end

方法b:
rails controller->action 代码:

复制代码 代码如下:

#post_controller::feed
def feed
@posts=post.find :all,:limit=>”id desc”
end

erb模板:

xml.instruct!
xml.rss(”version”=>”2.0″,
“xmlns:dc”=>”http://purl.org/dc/elements/1.1/”) do
xml.channel do
xml.title “renlu.xu 's blog”
xml.link(url_for(:action=>”start”,:only_path=>false))
xml.description “my life my love”
xml.language “zh_cn”
xml.ttl 60

for event in @posts do
xml.item do
xml.title(event.title)
xml.description(event.body)
xml.pubdate(event.created_at.to_s(:rfc822))
xml.guid(event.id)
xml.link(”http://…..#{event.id}”)
end
end
end
end

这种方法 网上很多文章到这一步就算完了,没有下文了,其实不对。到这一步,访问http://localhost:3000/post/feed仍然是出来的html的界面。g之,找到介绍:rails 2.0会根据不同的格式对模板进行渲染。这段代码放在/views/post/feed.rhtml中是没有用的,需要放在/views/post/feed.atom.builder中,并且需要通过http://localhost:3000/post/feed/123.atom(这里123没有什么实际意义 随便抓的一个),或是http://localhost:3000/post/feed?format=atom才能正确地按rss+xml输出。
软件
前端设计
程序设计
Java相关