3
\$\begingroup\$

I got sick of every time I make an Http request validating that the response was a success. I did a lot of:

if response.class == Net::HTTPOK

or

if response.is_a? Net::HTTPSuccess

I wanted something a little prettier so I came up with the following. I don't write a lot of class extensions like this so I wanted some input.

require 'net/http'
class Net::HTTPResponse
 def success?
 return false if ! self.is_a? Net::HTTPSuccess
 return true
 end
end

Now once the file is included I can say:

if response.success?
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 28, 2018 at 19:46
\$\endgroup\$
1
  • \$\begingroup\$ Just about every alternative to Net::HTTP has a better interface. Don't feel compelled to use it. \$\endgroup\$ Commented Mar 29, 2018 at 16:29

1 Answer 1

2
\$\begingroup\$

Though your solution would work, I would have gone for something like this:

class Net::HTTPResponse
 def success?
 false
 end
end
class Net::HTTPSuccess
 def success?
 true
 end
end

If you do keep your solution, you could simplify it to:

class Net::HTTPResponse
 def success?
 self.is_a? Net::HTTPSuccess
 end
end
answered Mar 29, 2018 at 15:29
\$\endgroup\$
1
  • \$\begingroup\$ A short comment about what like this or could simplify it to mean would be great ;-) \$\endgroup\$ Commented Mar 29, 2018 at 17:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.