Skip to content

Instantly share code, notes, and snippets.

@knittingdev
Created November 1, 2012 19:07
Show Gist options
  • Save knittingdev/3995757 to your computer and use it in GitHub Desktop.
Save knittingdev/3995757 to your computer and use it in GitHub Desktop.
Get Weather of Bloomberg's Top 50 Cities
require 'net/http'
require 'rexml/document'
class CityWeather
attr_reader :state, :city, :high, :low, :condition, :current
def initialize (state, city, high, low, condition, current)
@state = state
@city = city
@high = high
@low = low
@condition = condition
@current = current
end
end
def get_weather_data(woeid)
raw_xml = Net::HTTP.get_response(URI.parse(woeid)).body
doc = REXML::Document.new(raw_xml)
location = CityWeather.new(REXML::XPath.first(doc, '//@region').value,
REXML::XPath.first(doc, '//@city').value,
REXML::XPath.first(doc, '//@high').value.to_i,
REXML::XPath.first(doc, '//@low').value.to_i,
REXML::XPath.first(doc, '//@text').value,
REXML::XPath.first(doc, '//@temp').value.to_i)
end
def read_woeids
file = File.open('top50citieswoeids.txt')
source_trunk = "http://weather.yahooapis.com/forecastrss?w="
web_addresses = []
file.each do |line|
web_addresses << source_trunk + line
end
web_addresses
end
def time_it(woeids)
start_time = Time.now
city_weather = woeids.map{ |woeid| get_weather_data(woeid) }
city_weather.sort_by! { |location| [location.state, location.city]}
puts "Time to complete #{Time.now - start_time}s"
[city_weather, city_weather.max_by(&:current).city, city_weather.min_by(&:current).city]
end
def print(list, high_city, low_city)
col_width = list.map{|location| location.city.length}.max + 2
puts "State".ljust(col_width) + "City".ljust(col_width) +
"High".ljust(col_width) + "Low".ljust(col_width) +
"Condition".ljust(col_width) + "Current Temp".ljust(col_width)
list.each do |location|
puts location.state.ljust(col_width) + location.city.ljust(col_width) +
location.high.to_s.ljust(col_width) + location.low.to_s.ljust(col_width) +
location.condition.ljust(col_width) + location.current.to_s.ljust(col_width)
end
puts "High: #{high_city}"
puts "Low: #{low_city}"
end
woeids = read_woeids
city_weather, high_city, low_city = time_it(woeids)
print(city_weather, high_city, low_city)
2427690
2471390
2463583
2503863
2522292
2378015
2480201
2430683
2388929
2410128
2487796
2487129
2419946
2394734
2464592
2424766
2465512
2366355
2357024
2414469
2452078
2458833
2457170
2391279
2428344
2438841
2473224
2488042
23393762
2379200
2378426
2475687
2383489
2443945
2367105
2352824
2459115
2490383
2357536
2473475
2354490
2487956
2512636
2487889
2514815
2427665
2490057
2423945
2355942
2478307
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment