我正在使用Nokogiri从在线xml文档中获取一些天气数据,并且我想设置一个超时以便在无法到达源的情况下进行优雅恢复…
我的谷歌搜索显示了open-uri和Net :: HTTP的几种可能的方法,但没有特定于Nokogiri的方法.我尝试使用这些方法失败了(并不太令人惊讶):
begin currentloc = ("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + @destination.weatherloc) currentloc.read_timeout = 10 # doc = Nokogiri::XML(open(currentloc)) rescue Timeout::Error return "Current weather for this location not available: request timed out." end
返回“NoMethodError”,并且:
begin currentloc = ("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + @destination.weatherloc) doc = Nokogiri::XML(open(currentloc), :read_timeout => 10) rescue Timeout::Error return "Current weather for this location not available: request timed out." end
返回“TypeError无法将哈希转换为字符串”
Nokogiri是否支持这种方法(如果是这样……怎么样?),还是我应该考虑其他解决方案?
谢谢.
您可以使用超时模块:require 'open-uri' require 'nokogiri' require 'timeout' begin timeout(10) do result = Nokogiri::XML(open(currentloc)) end rescue Timeout::Error return "Current weahter..." end
精彩评论