Ruby on Rails勉強中。
エントリを投稿したらRSSを出力するようにしてみた。
果たしてこのやり方がRailsっぽいのかわからないので、かしこい人トラックバックしてください。
1.RSS生成クラスをhelpersに入れてみた。
rss_writer.rb
require 'rss/2.0'
require 'rss/maker'
class RssWriter
def output(entries)
rss = RSS::Maker.make('1.0') do |maker|
maker.channel.about = 'http://localhost:3000/index.rdf';
maker.channel.title = 'My RSS';
maker.channel.description = 'My description';
maker.channel.link = 'http://localhost:3000/blog';
entries.each do |entry|
item = maker.items.new_item;
item.link = 'http://localhost:3000/entry/show/' + entry.id.to_s;
item.title = entry.title;
item.description = entry.text;
item.date = Time.now;
end
end
f = open("public/index.xml", "w")
f.puts(rss.to_s)
f.close()
end
end
2.Entryモデルクラスのafter_saveコールバックを編集
entry.rb
require 'app/helpers/rss_writer'
class Entry < ActiveRecord::Base
def after_save
entries = Entry.find(省略)
writer = RssWriter.new
writer.output(entries)
end
end