如何用HTTParty解析wunderground api url中的变量?

时间:2012-09-07 21:30:56

标签: ruby-on-rails ruby ruby-on-rails-3

使用wunderground API在我的城市页面上显示天气预报。

city_controller.rb

def show

        @region = Region.find(params[:region_id])
        @city = City.find(params[:id])

        @weather_lookup = WeatherLookup.new

end

weather_lookup.rb

class WeatherLookup 
    attr_accessor :temperature, :icon, :condition

    def fetch_weather
      HTTParty.get("http://api.wunderground.com/api/a8135a01b8230bfb/hourly10day/lang:NL/q/IT/#{@city.name}.xml")
     end

    def initialize
      weather_hash = fetch_weather
    end

    def assign_values(weather_hash)
      hourly_forecast_response = weather_hash.parsed_response['response']['hourly_forecast']['forecast'].first
      self.temperature = hourly_forecast_response['temp']['metric']
      self.condition = hourly_forecast_response['condition']
      self.icon = hourly_forecast_response['icon_url']

   end

   def initialize
    weather_hash = fetch_weather
    assign_values(weather_hash)
   end

end

show.html.haml(城市)

= @weather_lookup.temperature 
= @weather_lookup.condition.downcase 
= image_tag @weather_lookup.icon

要获取正确的天气预报,我认为我可以将@city变量放在HTTParty.get URL中,就像我在示例中所做的那样,但是我得到错误消息undefined method`name'

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您需要WeatherLookup中的城市,则需要将其传递给初始化程序。实例变量仅绑定到各自的视图。

@weather_lookup = WeatherLookup.new(@city)

attr_accessor :city # optional

def initialize(city)
  @city = city
  weather_hash = fetch_weather
end