0

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' が表示されます。

ここで何が間違っていますか?

4

1 に答える 1

1

WeatherLookup で都市が必要な場合は、それを初期化子に渡す必要があります。インスタンス変数は、それぞれのビューにのみバインドされます。

@weather_lookup = WeatherLookup.new(@city)

attr_accessor :city # optional

def initialize(city)
  @city = city
  weather_hash = fetch_weather
end
于 2012-09-08T04:40:57.707 に答える