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()
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With