Livedoor Weather Hacksにアクセスしてみた。

現行の本家のバリアフリーグルメ検索サイトPHPで作られているのでPEAR::Services_Livedoorを使わせていただいているんですが、今Railsをいじっているので練習がてらRubyで天気予報を取得してみた。

以下、抜粋&メモ代わり

適当なrubyクラスでまず必要なライブラリをrequireしておきましょう。

require 'net/http'
require 'rexml/document'

次にコード。

  def livedoor_weather(city, day)
    res = nil
    begin
      uri = URI.parse("http://weather.livedoor.com/forecast/webservice/rest/v1?city=#{city}&day=#{day}")
      req = Net::HTTP::Get.new(uri.path + '?'+ uri.query) # <--一応動いているがエレガントでない例
      res = Net::HTTP.start(uri.host, uri.port) {|http|
        http.request(req)
      }
      rescue
      # TODO do something
    ensure
      if res
        return convert(res.body)
      else
        return convert( nil )
      end
    end
  end

  def convert(lwws_xml)
    weather_info = nil
    if lwws_xml
      weather_info = REXML::Document.new(lwws_xml)
    end
    # 必要な要素だけ取得
    @weather = Hash.new
    @weather['title']=(weather_info && weather_info.elements['lwws/title'].text) || '接続エラー'
    @weather['image_url']=(weather_info && weather_info.elements['lwws/image/url'].text) || '接続エラー'
    @weather['telop']=(weather_info && weather_info.elements['lwws/telop'].text) || '接続エラー'
    @weather['description']=(weather_info && weather_info.elements['lwws/description'].text) || '接続エラー'
    @weather['detail_url']=(weather_info && weather_info.elements['lwws/link'].text) || '接続エラー'
    @weather
  end

livedoor_weatherにcity(=1〜142の都市を表すID)とday(="today" or "tomorrow" or "dayaftertomorrow")を渡すと@weatherに天気が格納されます。もしくは@weatherが戻り値で返ってきます。

注意1
このまま使うと呼び出すたびにLivedoorのサイトにアクセスしてしまいます。Livedoorにも負荷かかりますし、Livedoorが重くなったりすると呼び出す側もまたされますから誰も幸せになれません。適切なキャッシュを保存して、キャッシュが古かったらLivedoorにアクセスするように作りましょう。