ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

RSSフィードを追加してみる。

http://d.hatena.ne.jp/taka_2/20080521#p1
で、RSSサポートやるかも。とか書いたのでやってみる。


RSSを扱うためのライブラリはRubyに添付されているので、それを使う。
http://doc.loveruby.net/refm/api/view/library/rss
ちなみに、RSSの仕様は単純っぽいが、バージョンとか経緯とかは色々複雑みたい。
http://ja.wikipedia.org/wiki/RSS
RSS2.0がRSS1.0の上位互換じゃないってありえん。


とりあえず、library rssのサンプル通りに作ってみる。
app/controllers/products_controller.rb

  def index_rss
    rss = RSS::Maker.make("1.0") do |maker|
      maker.channel.about = "http://example.com/index.rdf"
      maker.channel.title = "Example"
      maker.channel.description = "Example Site"
      maker.channel.link = "http://example.com/"
    end

    render(:text => rss.to_s)
  end

これで、
http://localhost:3000/products/index_rss/1
にアクセス。

出ました。
firefoxだとこんな感じで表示されるのですね。


せっかくなので、product一覧をRSSフィードで配信してみましょう。
app/controllers/products_controller.rb

  def index_rss
    @products = Product.find(:all)

    rss = RSS::Maker.make("1.0") do |maker| 
      maker.channel.about = "http://example.com/index.rdf"
      maker.channel.title = "Example"
      maker.channel.description = "Example Site"
      maker.channel.link = "http://example.com/"

      for product in @products
        item = maker.items.new_item
        item.link = url_for(:action => :show, :id => product.id)
        item.title = product.title
        item.date = Time.parse(product.updated_at.to_s)
      end     
    end

    render(:text => rss.to_s)
  end

このフィードを購読すると、新しい商品が追加される度に通知されますよ。