четвер, 11 березня 2010 р.

Yahoo! Weather і Ruby

Yahoo! Weather RSS-канал дозволяє отримувати останню інформацію про погоду для вашої місцевості. Ви можете зберігати цю інформаію у вашому улюбленому RSS-агрегаторі, або включити ці дані до вашого сайту або додатку. RSS динамічно генерується на основі WOEID.

Короткий опис формату запиту URL та RSS відповіді.
Запит RSS слідує наступному простому синтакстису HTTP GET: починається з простого базого URL за яким слідують додаткові параметри і значення після знаку питання (?). Кілька параметрів розділяються амперсандом (&).
Базовий URL для каналу погоди є
http://weather.yahooapis.com/forecastrss
Два можливі параметри:
  • w - для WOID (обов'язковий параметр, що вказує на місце розташування для прогнозу погоди). Наприклад w=935810
  • u - для одиниць вимірювання(c: за Цельсієм, f: за Фаренгейтом). Наприклад u=c. Вибір 'c' покаже всі дані в метричних одиницях(наприклад швидкість вітру буде відображатися в кілометрах за годину).
http://weather.yahooapis.com/forecastrss?w=location

Наприклад, щоб отримати погоду для Тернополя, використовується код 935810.
http://weather.yahooapis.com/forecastrss?w=935810

Щоб знайти значення WOID для вашого міста, здійсність пошук на головній сторінці.
Наприклад для Тернополя, URL сайту буде мати наступний вигляд:
http://weather.yahoo.com/ukraine/ternopil-oblast/tarnopol'-935810/
Де WOID це 935810.

RSS відповідь я не буду докладно описувати.
Знизу приведений приклад коду для роботи з Yahoo! Weather з Ruby.


require 'nokogiri'
require 'open-uri'
require 'time'

class YWeather
  attr_reader :code

  def initialize(code, units = 'c')
    @units = units
    @code = code
    url = "http://weather.yahooapis.com/forecastrss?w=#{@code}&u=#{@units}"
    @doc = Nokogiri::XML(open(url))
  end

  def pub_date
    Time.parse(@doc.xpath('//pubDate').text)
  end

  def location
    location = @doc.xpath('//yweather:location')
    return {:city => location.attr('city').value,
            :region => location.attr('region').value,
            :country => location.attr('country').value
    }
  end

  def units
    units = @doc.xpath('//yweather:units')
    return {:temperature => units.attr('temperature').value,
            :distance => units.attr('distance').value,
            :pressure => units.attr('pressure').value,
            :speed => units.attr('speed').value
    }
  end

  def astronomy
    astronomy = @doc.xpath('//yweather:astronomy')
    return {:sunrise => astronomy.attr('sunrise').value,
            :sunset => astronomy.attr('sunset').value
    }
  end

  def atmosphere
    atmosphere = @doc.xpath('//yweather:atmosphere')
    return {:humidity => atmosphere.attr('humidity').value,
            :visibility => atmosphere.attr('visibility').value,
            :pressure => atmosphere.attr('pressure').value,
            :rising => atmosphere.attr('rising').value
    }
  end

  def condition
    condition = @doc.xpath('//yweather:condition')
    return {:text => condition.attr('text').value,
            :code => condition.attr('code').value.to_i,
            :temp => condition.attr('temp').value,
            :date => condition.attr('date').value
    }
  end

  def wind
    wind = @doc.xpath('//yweather:wind')
    return {:chill => wind.attr('chill').value,
            :direction => wind.attr('direction').value,
            :speed => wind.attr('speed').value
    }
  end

  def forecast
    forecast = @doc.xpath('//yweather:forecast')
    f = []
    forecast.each do |item|
      f << {:date => Time.parse(item.attr('date')),
            :low => item.attr('low'),
            :high => item.attr('high'),
            :code => item.attr('code')}
    end

    return f
  end

end


if __FILE__ == $0
  location_code = "12518451"
  weather = YWeather.new(location_code)
  puts weather.location
  puts weather.pub_date
  puts weather.condition[:temp] + weather.units[:temperature]
  puts weather.wind[:speed] + weather.units[:speed]
  puts weather.astronomy
  puts weather.atmosphere
  puts weather.forecast
end

Докладніше про Yahoo! Weather RSS feed тут

Немає коментарів: