ActiveResourceでライブドアお天気Webサービスを利用する
作成中のアプリで明日の天気を表示したかったので、試してみました。
ActiveResourceを使うのは初めてなのでけっこう悩みましたが、出来てみれば意外に簡単。
環境
- Rails 2.3.5
- Ruby 1.8.7
モデル
ActiveRecordをActiveResourceに変えて、siteを設定します。
ベースURL
http://weather.livedoor.com/forecast/webservice/rest/v1
以下のようになります。
class Livedoorweather < ActiveResource::Base self.site = "http://weather.livedoor.com/" def self.tomorrow(city) Livedoorweather.find(:one, :from => "/forecast/webservice/rest/v1", :params => {:city => city, :day => "tomorrow"}) end end
コントローラー
ActiveRecordと何も変わりません。
class LivedoorweathersController < ApplicationController def show @weather = Livedoorweather.tomorrow(params[:id]) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @weather } end end end
ビュー
属性と階層は、関連のようにアクセスできます。
属性
<location area="九州" pref="福岡県" city="久留米" />
<p> <b>area:</b> <%=h @weather.location.area %> </p> <p> <b>pref:</b> <%=h @weather.location.pref %> </p> <p> <b>city:</b> <%=h @weather.location.city %> </p>
階層
<image> <title>晴れ</title> <link>http://weather.livedoor.com/area/40/113.html?v=1</link> <url>http://weather.livedoor.com/img/icon/1.gif</url> <width>50</width> <height>31</height> </image>
<p> <b>image.title:</b> <%=h @weather.image.title %> </p> <p> <b>image.link:</b> <%=link_to @weather.image.link, @weather.image.link, {:popup => "true" } %> </p> <p> <b>image.url:</b> <%=image_tag @weather.image.url %> </p>
通常のレベルはこんな感じ。
<title>福岡県 久留米 - 明日の天気</title>
<p> <b>title:</b> <%=h @weather.title %> </p>
繰り返しの部分はこんな感じ。
<pinpoint> <location> <title>大牟田市</title> <link>http://weather.livedoor.com/point/city/2130.html</link> <publictime>Thu, 26 Jan 2006 16:00:00 +0900</publictime> </location> <location> <title>久留米市</title> <link>http://weather.livedoor.com/point/city/2131.html</link> <publictime>Thu, 26 Jan 2006 16:00:00 +0900</publictime> </location> <location> <title>柳川市</title> <link>http://weather.livedoor.com/point/city/2135.html</link> <publictime>Thu, 26 Jan 2006 16:00:00 +0900</publictime> </location> </pinpoint>
<table class="table"> <tr> <th>title</th> <th>link</th> <th>publictime</th> </tr> <% @weather.pinpoint.location.each do |location| %> <tr> <td><%=h location.title %></td> <td><%=link_to location.link, location.link %></td> <td><%=h location.publictime %></td> </tr> <% end %> </table>