lib/kisyo/daily.rb in kisyo-0.0.2 vs lib/kisyo/daily.rb in kisyo-0.0.3

- old
+ new

@@ -1,18 +1,27 @@ require 'nokogiri' require 'open-uri' module Kisyo class Daily + CACHE_SIZE = 100 + def initialize(location) @location = location + @cache = Cache.new end def at(date) + key = [date.year, date.month, date.day].join(',') + + if value = cache.get(key) + return value + end + url = 'http://www.data.jma.go.jp/obd/stats/etrn/view/daily_s1.php?prec_no=%i&block_no=%i&year=%i&month=%i&day=01&view=p1' % [ - @location.prefecture_id, - @location.block_id, + location.prefecture_id, + location.block_id, date.year, date.month ] content = open(url).read @@ -20,15 +29,20 @@ days = doc.css('div.a_print') raise WeatherInformationNotAvailable if days.size == 0 days.each do |el| - if el.text.to_i == date.day - tr = el.parent.parent - values = tr.css('td').map(&:text) + tr = el.parent.parent + values = tr.css('td').map(&:text) - return Element::Day.new(*values[1 .. -1]) - end + k = [date.year, date.month, values[0]].join(',') + cache.set(k, Element::Day.new(*values[1 .. -1])) end + + cache.get(key) end + + private + + attr_reader :cache, :location end end