Skip to content

Instantly share code, notes, and snippets.

@hachibeeDI
Created June 14, 2013 04:37
Show Gist options
  • Save hachibeeDI/5779490 to your computer and use it in GitHub Desktop.
Save hachibeeDI/5779490 to your computer and use it in GitHub Desktop.
# -*- encoding: UTF-8 -*-
require 'net/http'
require 'uri'
require 'rexml/document'
class Weather
@@signs = {"くもり" => "☁" \
, "雨" => "☂" \
, "晴れ" => "☀" \
, "雪" => "☃" \
}
def initialize(node)
get_elem = Proc.new {|tag| node.elements[tag].text }
@weather = get_elem.call('weather')
@temperature_max = get_elem.call("temperature/range[@centigrade='max']")
@temperature_min = get_elem.call("temperature/range[@centigrade='min']")
@chance_of_rain_nodes_par_hours = node.elements.each("rainfallchance/period") do |el|
el
end
end
def weather_as_sign()
sygned = @weather.split(/[一時\|のち\|時々]/).select{|s| s != ""}.map {|s| @@signs[s]}
return sygned.join()
end
def near_chance_of_rain()
now_hour = Time.now.hour.to_i
nearest_chance = @chance_of_rain_nodes_par_hours.find do |el_node|
targ_times = el_node.attributes['hour'].split('-').map {|s| s.to_i}
now_hour.between?(targ_times[0], targ_times[1])
end
return nearest_chance.text + "%"
end
attr_accessor :weather, :temperature_max, :temperature_min, :chance_of_rain
end
CITY_MAP = {:tokyo => '13'}
def get_weather_xml(city)
uri = URI("http://www.drk7.jp/weather/xml/#{CITY_MAP[city]}.xml")
Net::HTTP.get(uri)
end
def parse_tokyo_info(weather_info)
doc = REXML::Document.new(weather_info)
areas = doc.elements["weatherforecast/pref/area[@id='東京地方']"]
gen = Enumerator.new do |__yield|
areas.elements.each('info') do |element|
__yield << Weather.new(element)
end
end
return gen
end
if __FILE__ == $0
info = parse_tokyo_info(get_weather_xml(:tokyo))
# 日付順なので一番上が当日の日付になる
today_info = info.first
puts "weather: #{today_info.weather_as_sign()} - #{today_info.near_chance_of_rain()}"
puts "temperature: #{today_info.temperature_min} - #{today_info.temperature_max}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment