Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set read_timeout for the service call in Ruby Net::HTTP.start

I want to override the default timeout for the service call in my ruby code. I open connection as under.

res = Net::HTTP.start(@@task_url.host, @@task_url.port) do |http|
    http.get("/tasks/#{task_id}")
end          

I tried to set the read_timeout time as under but then I got the NoMethodError exception in my code.

res = Net::HTTP.start(@@task_url.host, @@task_url.port)
res.read_timeout = 10
res do |http|
    http.get("/tasks/#{task_id}")
end

Suggest me how should I set the read_timeout. And I am looking to set the read_timeout somewhere globally so that I can use that timeout for all my service call through Net::HTTPP.start()

like image 206
manyu Avatar asked Mar 01 '13 12:03

manyu


2 Answers

If you use Ruby 1.8 you have to use Net::HTTP.new:

http = Net::HTTP.new(host, port)
http.read_timeout = 10

response = http.get("/")    
# or intead of above line if you need block
# http.start do
#   response = http.get("/")
# end

If you look at the source code of Net::HTTP.start, you will see that ::start is just calling ::new with #start method:

# File net/http.rb, line 439
def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
  new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
end

>= Ruby 1.9

You can set read_timeout in opt argument: start(address, ..., opt, &block)

like this:

res = Net::HTTP.start(host, port, :read_timeout => 10)
like image 76
A.D. Avatar answered Nov 15 '22 20:11

A.D.


You could use open from OpenURI. This method has a :read_timeout option. I don't know how to set the option globally, but you can wrap it inside a custom function that sets this option.

require 'open-uri'
module NetCustom

  def open_url(url, &task)
     open(url, :read_timeout => 20) do |file|
       yield file.read
     end
  end

end

Usage:

class Foo
  include NetCustom

  def bar
    open_url('http://example.org/tasks/') do |content|
      # Handle page text content
    end
  end
end
like image 43
Baldrick Avatar answered Nov 15 '22 21:11

Baldrick