Check Ruby HTTP response for success

cbmanica picture cbmanica · Aug 19, 2012 · Viewed 38.2k times · Source

How does one properly check the response from Net::HTTP::Get (for example) for "success" (i.e., a 2xx return code)? The documentation seems to be sadly silent on this simple question.

I have:

response=Net::HTTP.new( host, port ).request my_get_request # details not important

After a bunch of Googling and near-random typing, I finally determined that this works:

response.class < Net::HTTPSuccess

Is that actually the canonical way to do it?

Answer

Andrew Marshall picture Andrew Marshall · Aug 19, 2012

For Net::HTTP, yes, checking the class of the response object is the way to do it. Using kind_of? is a bit clearer (but functionally equivalent to using <):

response.kind_of? Net::HTTPSuccess

Calling value on response will also raise a Net::HTTPError if the status code was not a successful one (what a poorly named method…).

If you can, you may want to consider using a gem instead of Net::HTTP, as they often offer better APIs and performance. Typhoeus and HTTParty are two good ones, among others.