地名しりとりにフィードをつけた (FeedTools)
地名しりとりの履歴を見ていると、知らない地名が出てきて面白い。
- 土々呂町 (ととろまち) ← トトロの町!?
- 十年明 (じゅうねんみょう)
- 志布志市 (しぶしし)
RSS リーダーで履歴が見れたほうが便利だと思った。 ちょうど、 Rails 勉強会で「フィードとキャッシュ」のセッションに出たので、 そこで紹介された FeedTools を使ってみることにした。
インストール
RubyGems 一発。関連するパッケージもインストールされた気がする。
$ sudo gem install -r feedtools
しりとりエンジンの改造
FeedTools の使い方は簡単。 かなり直感的に書けた。
まずは History モデルに feed クラスメソッドを追加。
Index: app/models/history.rb =================================================================== --- app/models/history.rb (リビジョン 9) +++ app/models/history.rb (作業コピー) @@ -1,3 +1,6 @@ +require 'rubygems' +require 'feed_tools' + # しりとりのための基本文字列の拡張 class String # 文字列の先頭の1文字を返す(マルチバイト対応) @@ -77,4 +80,24 @@ area.save end end + + def self.feed + feed = FeedTools::Feed.new + feed.title = "地名しりとり" + feed.subtitle = "地名しりとりに追加された地名" + feed.author.name = "capping.machu.jp" + feed.link = "http://capping.machu.jp/" + + histories = find(:all, :include => :area, :order => 'histories.id DESC', :limit => 20) + feed.updated = histories[0].created_on + histories.each do |history| + item = FeedTools::FeedItem.new + item.title = history.area.name + item.link = "http://capping.machu.jp/" + item.content = "#{history.area.name} (#{history.area.syllabary}) #{history.area.full_name}" + item.updated = history.created_on + feed.entries << item + end + feed.build_xml("atom", 1.0) + end end
ソースの解説は多分いらないと思う。最近の20件の履歴を FeedItem として登録して、最後に build_xml を実行するだけ。 次にコントローラにアクションを追加する。
Index: app/controllers/histories_controller.rb =================================================================== --- app/controllers/histories_controller.rb (リビジョン 9) +++ app/controllers/histories_controller.rb (作業コピー) @@ -69,4 +69,9 @@ expire_action :action => 'history' redirect_to :action => 'index' end + + def feed + headers['Content-Type'] = 'text/xml;charset=utf-8' + render(:text => History.feed) + end end
headers を使って、出力時の Content-Type を変えている(デフォルトでは text/html になるため)。 最後にビューに Auto Discovery を追加する。
Index: views/histories/index.rhtml =================================================================== --- views/histories/index.rhtml (リビジョン 9) +++ views/histories/index.rhtml (作業コピー) @@ -6,6 +6,7 @@ <title>地名しりとり</title> <link href="http://www.google.com/uds/css/gsearch.css" rel="stylesheet" type="text/css"/> <link href="/stylesheets/capping.css" rel="stylesheet" type="text/css"/> +<link rel="alternate" type="application/rss+xml" title="RSS" href="/histories/feed"> <script type="text/javascript" src="/javascripts/prototype.js"></script> <script src="http://maps.google.co.jp/maps?file=api&v=2&key=<%=h GOOGLE_MAPS_API_KEY %>" type="text/javascript"></script> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=<%=h GOOGLE_AJAX_SEARCH_API_KEY %>" type="text/javascript"></script>
これだけでおしまい。地名しりとりのサイトにアクセスしたら、ちゃんとフィードアイコンが表示されるようになった。 簡単だった。