module NationalWeather

Constants

VERSION

Public Class Methods

current(station_id) click to toggle source

Returns the current weather conditions at the station id specified, or nil if there was an error. For the station ID see: www.weather.gov/xml/current_obs/ XML list of stations: www.weather.gov/xml/current_obs/index.xml

# File lib/nationalweather.rb, line 18
def NationalWeather::current(station_id)
  xml = fetch("http://w1.weather.gov/xml/current_obs/#{station_id}.xml")
  NationalWeather::Current.new(xml)
end
forecast(lat, lng, start_date, days) click to toggle source

Returns the forecast for the given location, or nil if there was an error. start_date expected in YYYY-MM-DD format

# File lib/nationalweather.rb, line 25
def NationalWeather::forecast(lat, lng, start_date, days)
  xml = fetch("http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdBrowserClientByDay.php?lat=#{lat.to_s}&lon=#{lng.to_s}&format=24+hourly&numDays=#{days.to_s}&startDate=#{start_date}")
  NationalWeather::Forecast.new(xml)
end

Private Class Methods

fetch(uri_str, limit = 10) click to toggle source

Returns the XML response string for the given URL, following redirects along the way

# File lib/nationalweather.rb, line 41
def NationalWeather::fetch(uri_str, limit = 10)

  # TODO: optional file cache

  raise NationalWeather::TooManyRedirectsError, 'Too many HTTP redirects.' if limit == 0

  uri = URI(uri_str)
  req = Net::HTTP::Get.new(uri)
  req['User-Agent'] = "amwhalen-ruby-nationalweather-#{NationalWeather::VERSION}"

  response = Net::HTTP.start(uri.hostname, uri.port) {|http|
    http.request(req)
  }

  case response
  when Net::HTTPSuccess then
    response.body.to_s
  when Net::HTTPRedirection then
    location = response['location']
    fetch(location, limit - 1)
  else
    raise NationalWeather::BadHTTPResponseError, "Bad return value: #{response.value}"
  end
end