jnunemaker / httparty

:tada: Makes http fun again!
MIT License
5.81k stars 964 forks source link

Adding Response Code Helper Methods like _401? #788

Open baxter2 opened 1 year ago

baxter2 commented 1 year ago

While working on a project, I often encountered scenarios where I was checking the response code to handle specific HTTP status codes. For instance:

HTTParty.get(
  "https://example.com/endpoint",
  headers: { "x-media-mis-token" => token }
).tap { |res| raise TokenExpiredError if res.code == 401 }

This made me think about the readability and expressiveness of the code. The standard approach, res.code == 401, gets the job done, but I wondered if we could introduce helper methods like _401? to make this even clearer.

With the proposed change, the above example could look like this:

HTTParty.get(
  "https://example.com/endpoint",
  headers: { "x-media-mis-token" => token }
).tap { |res| raise TokenExpiredError if res._401? }

I understand that in Ruby, methods can't begin with a number, so I've prefixed it with an underscore. I know this might not be everyone's favorite syntax, so I'm very open to feedback or alternative naming suggestions.

Why is this beneficial?

  1. Readability: The code's intent becomes very clear.
  2. Expressiveness: It aligns with the Ruby idiom of providing ? methods for conditions.
  3. Convenience: Especially when dealing with multiple status checks, this can make the code look cleaner. Would love to hear your thoughts on this. If it's something the community feels is valuable, I'd be willing to look into helping with implementation. Otherwise, if it's deemed not to fit the direction or philosophy of the library, no worries at all.
chelobotix commented 6 months ago

Hello, I'm new around here. What do you think about to use the same Rails Satus code? https://gist.github.com/mlanett/a31c340b132ddefa9cca

jnunemaker commented 6 months ago

I'm on the fence for helper methods. I like them but it also could collide with the underlying response that is being delegated to normally. I don't like underscore prefixed, but the methods from that gist seem do-able. Not sure how often most of them would get used as I assume people wouldn't remember what method name matches to what status code.