Open-URI is convenient, but this ease of use means that they remove access to many configuration details that other HTTP clients, such as Net :: HTTP, can use.
It depends on which version of Ruby you are using. For 1.8.7 you can use the Timeout module. From the docs:
require 'timeout' begin status = Timeout::timeout(5) { getresult = open(cstr, "UserAgent" => "Ruby-OpenURI").read } rescue Timeout::Error => e puts e.to_s end
Then check the getresult length to see if you have content:
if (getresult.empty?) puts "got nothing from url" end
If you are using Ruby 1.9.2, you can add :read_timeout => 10 the open() parameter.
In addition, your code can be tightened and made a little more flexible. This will allow you to pass the URL or use the URL used by default. Also read the Nokogiri NodeSet to understand the difference between xpath , / , css and at , % , at_css , at_xpath :
def get_name_from_remote_url(cstr = 'http://someurl.com') doc = Nokogiri::XML(open(cstr, 'UserAgent' => 'Ruby-OpenURI'))
the tin man
source share