4

I'm fetching some weather data from an online xml doc using Nokogiri, and I would like to set up a timeout for graceful recovery in case the source can't be reached...

My google searches show several possible methods for open-uri and Net::HTTP, but none specific to Nokogiri. My attempts to use those methods are failing (not too surprisingly):

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

returns "NoMethodError", and:

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

returns "TypeError can't convert Hash into String"

Does Nokogiri support this kind of method (and if so... how?), or should I be looking at some other solution?

Thanks.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261

1 Answers1

4

You can use the timeout module :

require 'open-uri'
require 'nokogiri'
require 'timeout'

begin
  timeout(10) do
    result = Nokogiri::XML(open(currentloc))
  end
rescue Timeout::Error
  return "Current weahter..."
end
Vincent
  • 4,883
  • 2
  • 25
  • 17
  • This appears to work (at least it doesn't break), but when I try to test it by disconnecting eth0, I'm getting a SocketError. I guess I need some sort of conditional test for that, too. Adding an extra rescue statement (rescue SocketError) is failing, however. Thanks –  Sep 26 '09 at 15:11
  • Can you post your code so I can see for myself in greater detail? – Vincent Sep 27 '09 at 00:12