Determining success for a Faraday request
Asked Answered
S

1

6

I've adopted some code which has like 5 or 6 Faraday requests inline and is my first time working with it. I am abstracting out to a module. This is the first time I am using this library and I currently have:

module CoreService
  def self.net_connection param_url
    conn = Faraday.new(:url => param_url ) do |c|
      c.use Faraday::Request::UrlEncoded  # encode request params as "www-form-urlencoded"
      c.use Faraday::Response::Logger     # log request & response to STDOUT
      c.use Faraday::Adapter::NetHttp     # perform requests with Net::HTTP
    end
    return conn
  end

  def self.success? arg
    if [200,302].include? arg.status
      return true
    else
      return false
    end
  end
end

and would use like:

conn=CoreService.net_connection SOME::URL
url_val = "/other/things"
response = conn.get url_val     

if CoreService.success? response
  puts "THAT WAS A SUCCESS"
else
  puts "THAT WAS NOT A SUCCESS"
end

However, this feels a bit inelegant. Would I be better off writing this differently such as monkeypatching the response? The current Faraday response bojects supports a success? instance method but that is only checking for 200.

Sabayon answered 10/5, 2015 at 5:22 Comment(0)
P
5

As per VERSION = '1.0.0' there is a response.success? method which returns true on http response codes 200 to 299

See: https://github.com/lostisland/faraday/blob/e2c56e90c9b12f69f84a536ae341617672bd52b7/lib/faraday/options/env.rb#L57

Plumule answered 27/2, 2020 at 1:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.