12

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()

1

2 Answers 2

20

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) 
Sign up to request clarification or add additional context in comments.

13 Comments

Can you post somewhere (gist.github.com) piece of code you're trying?
Try irb, just require "net/http"; res = Net::HTTP.start(your_host, your_port, :read_timeout => 10) if it works.
actually i think signature expects other values to be passed in the method as well. So will not try by passing other parameters as nul
Yes try it with other params with nil, but it's strange, because it works for me without problem.
Running in irb gives the same TypeError cannot convert hash to string
|
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.