首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用HTTPParty解析wunderground url中的变量?

如何用HTTPParty解析wunderground url中的变量?
EN

Stack Overflow用户
提问于 2012-09-08 05:30:56
回答 1查看 535关注 0票数 0

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

city_controller.rb

代码语言:javascript
复制
def show

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

        @weather_lookup = WeatherLookup.new

end

weather_lookup.rb

代码语言:javascript
复制
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(城市)

代码语言:javascript
复制
= @weather_lookup.temperature 
= @weather_lookup.condition.downcase 
= image_tag @weather_lookup.icon

为了获取正确的天气预报,我认为我可以像在示例中那样将@ HTTParty.get变量放在`name地址中,但我得到了错误消息undefined method ` `name‘。

我在这里做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-08 12:40:58

如果你需要WeatherLookup中的城市,你需要把它传递给初始化器。实例变量仅绑定到其各自的视图。

代码语言:javascript
复制
@weather_lookup = WeatherLookup.new(@city)

代码语言:javascript
复制
attr_accessor :city # optional

def initialize(city)
  @city = city
  weather_hash = fetch_weather
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12325665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档