One that caught me out for a while … needed to reduce the timeout the Net/HTTP library was defaulting to because the servers I was querying were liable to be offline and I didn’t want my script hanging around.
I wrote something like:
require 'net/http'
res = Net::HTTP.start('http://www.example.com') do |http|
http.open_timeout = 4
http.read_timeout = 4
http.get('/index.html')
end
puts res.body
Pah, why does Ruby seem to totally ignore the timeout settings? It just ignores it… humm. Okay some digging required. It would appear the instance method invokes the connect then yields so by the time the block is actually executed the connection has already been attempted, with the default timeouts - rather than those that appears to be set.
So we need to use code akin to:
require 'net/http'
http = Net::HTTP.new("http://www.example.com")
http.open_timeout = 4
http.read_timeout = 4
res = http.get('/index.html')
puts res.body
For it to respect our timeouts!
Written on 16 Dec 2010 and categorised in Ruby, tagged as