12

Is there a way to add timeout options in this simple get method?

I am using Faraday 3.3.

Faraday.get(url)

After searching around, I can only apply timeout options after I initiate a connection first, then apply timeout options. Or there's a simple way?

This is what I am doing right now:

conn = Faraday.new
response = conn.get do |req|
  req.url url
  req.options.timeout = 2 # 2 seconds
end
Jared Beck
  • 16,796
  • 9
  • 72
  • 97
Zhaohan Weng
  • 378
  • 1
  • 4
  • 10

2 Answers2

22

Try this one:

conn = Faraday.new do |conn|
  conn.options.timeout = 20
end
response = conn.get(url)

UPD: After I had reviewed gem sources, I found out that there's no way do it like you want.

With get method you can set only url, request params and headers. But to specify timeout, you have to access @options of Faraday::Connection instance. And you can do this by using attr_reader :options

conn = Faraday::Connection.new
conn.options.timeout = 20

Or on initialization of Faraday::Connection instance:

Faraday::Connection.new(nil, request: { timeout: 20 })

Or when it copies connection parameters to request parameter and yields request back:

Faraday::Connection.new.get(url) { |request| request.options.timeout = 20 }
Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24
Alexander Karmes
  • 2,438
  • 1
  • 28
  • 34
  • thanks, this is similar to what I have. I was think if there's a way just pass the options in in the Faraday.get right away. – Zhaohan Weng Aug 28 '15 at 14:15
  • Thanks so much for the clarification. – Zhaohan Weng Aug 28 '15 at 22:19
  • There are other timeouts that can be set: I use `open_timeout` often, which is the timeout for opening the TCP connection. There's also a `read_timeout` and `write_timeout`, I think. – Jared Beck Aug 15 '22 at 21:28
0

I had the same problem and I ended up doing something like this so I can more easily stub the code in testing:

    def self.get(url, params: {}, headers: {}, timeout: 2)
      conn = Faraday.new(
        params: params,
        headers: headers
      ) do |conn|
        conn.options.timeout = timeout
      end

      conn.get(url)
    end
hakunin
  • 4,041
  • 6
  • 40
  • 57