Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Open-URI is convenient, but that ease of use means they're removing the access to a lot of the configuration details the other HTTP clients like Net::HTTP allow.</p> <p>It depends on what version of Ruby you're using. For 1.8.7 you can use the <a href="http://rubydoc.info/stdlib/timeout/1.9.2/frames" rel="nofollow noreferrer">Timeout</a> module. From the docs:</p> <pre><code>require 'timeout' begin status = Timeout::timeout(5) { getresult = open(cstr, "UserAgent" =&gt; "Ruby-OpenURI").read } rescue Timeout::Error =&gt; e puts e.to_s end </code></pre> <p>Then check the length of getresult to see if you got any content: </p> <pre><code>if (getresult.empty?) puts "got nothing from url" end </code></pre> <p>If you are using Ruby 1.9.2 you can add a <a href="http://rubydoc.info/stdlib/open-uri/1.9.2/frames" rel="nofollow noreferrer"><code>:read_timeout =&gt; 10</code></a> option to the <code>open()</code> method.</p> <hr> <p>Also, your code could be tightened up and made a bit more flexible. This will let you pass in a URL or default to the currently used URL. Also read Nokogiri's <a href="http://rubydoc.info/gems/nokogiri/1.4.4.2/frames" rel="nofollow noreferrer">NodeSet</a> docs to understand the difference between <code>xpath</code>, <code>/</code>, <code>css</code> and <code>at</code>, <code>%</code>, <code>at_css</code>, <code>at_xpath</code>:</p> <pre><code>def get_name_from_remote_url(cstr = 'http://someurl.com') doc = Nokogiri::XML(open(cstr, 'UserAgent' =&gt; 'Ruby-OpenURI')) # xpath returns a nodeset which has to be iterated over # my_data = doc.xpath('/session/name').text # =&gt; 'Fred' or 'Sam' etc # at returns a single node doc.at('/session/name').text end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload