MerbアプリケーションでAtomフィードを配信する方法のメモです。
まずは、config/dependencies.rbに、利用するGemを登録します。
1 dependency "merb-builder"
2 dependency "merb_full_url"
merb_full_url
は、フィード中で埋め込まれる
absoluteなURLを生成するためのプラグインです。
以下のようにインストールできます。
1 % sudo gem install merb_full_url --source http://merbi.st
次に、コントローラのindexアクションで
atomフィードを提供する事を指示します。
1 def index
2 provides :atom
さらに、config/init.rbで、MIMEタイプとしてatomを登録します。
1 Merb::BootLoader.before_app_loads do
2
3 Merb.add_mime_type(:atom, :to_atom, %w[application/atom+xml])
4 end
5
続いて、フィードを生成するためのindex.atom.builderファイルを
app/views/{resource_name}の下に作ります。
このあたりはRailsのXmlBuilderと同じような感じです。
1 xml.instruct! :xml, :version=>"1.0"
2 xml.feed(:xmlns => "http://www.w3.org/2005/Atom") do |feed|
3 feed.title @title
4 feed.link :type => 'text/html', :rel => 'alternate',
5 :href => full_resource(:posts)
6
7 @posts.each do |post|
8 feed.entry do |entry|
9 entry.id post.id
10 entry.title post.title
11 entry.content post.body, :type => 'text'
12 entry.issued post.created_at
13 entry.modified post.updated_at
14 entry.link :type => "text/html", :rel => "alternate",
15 :href => full_resource(post)
16 entry.author do |author|
17 author.name post.user.login
18 end
19 end
20 end
21 end
以上で完了。これで後は/{resource_name}.atom
にアクセスすれば、フィードが表示されます。
ちなみに、Vimでmerb.vimを使っている場合、.builderのfiletype
を認識させるために、.vim/ftdetect/merb.vimの中で、
以下の1行を加えると、正しくファイルタイプを認識してくれます。
1 au BufRead,BufNewFile */app/{mailers/,}views/*.builder set ft=ruby.merb_controller