031-Sinatra+MongoDBでブロガー情報
あすなろBLOGを巡回するcrawlerは出来たので、JSON形式で値を返すWebアプリが必要なので、Sinatra使って実装し始めています。
どんな仕様にするか
http://xxxx.xxx/api/yokota.json
http://xxxx.xxx/api/oohashi.json
:
という感じで、
/api/ブロガーの名前.json
でアクセスすれば、そのブロガーの更新情報をJSON形式で取得できるという仕様を考えてます。
とりあえずHTML形式で表示できるように実装
SinatraはHello World!的なサンプルをちょっと書いたことがある程度だったので、第9回 SinatraとSequel・Hamlで掲示板アプリを作るを参考にしてひとまずHTML形式で表示できるように実装してみました
# app.rb require 'rubygems' require 'sinatra' require 'json' require 'entry.rb' require 'haml' get '/api/:name.html' do blogger = params[:name] @items = Entry.find(:conditions => {:blogger => blogger}) haml :layout end
上記app.rbで利用しているhamlは、views/layout.htmlに配置しておき、中身をこんな感じにしました。
!!! XML !!! Strict %html %head %title あすなろBLOG %meta{:"http-equiv"=>"Content-Type", :content=>"text/html", :charset=>"utf-8"} %link{:rel=>"stylesheet", :type=>"text/css", :href=>"/style.css"} %body - @items.each do |item| .item %h2= item.title %a{:href => item.permalink} permalink %p= item.html_body
これで意図したように表示はできるので、これをベースにJSON形式で出力できるアプリを作れれば、あすなろBLOG Reader for iPhoneの完成に近づくように感じます