httparty
httparty copied to clipboard
Adding Response Code Helper Methods like _401?
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?
- Readability: The code's intent becomes very clear.
- Expressiveness: It aligns with the Ruby idiom of providing ? methods for conditions.
- 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.