rails製作rss feed代碼

來源:互聯網
上載者:User

方法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://up-u.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輸出。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.