-1

I was curious when building a method to call an endpoint using the Net::HTTP library in rails. As the endpoint I was calling accepted the same body but with multiple request methods, I wanted to dynamically call Net::HTTP.

To do this, I used this concoction

req_method = Object.const_get "Net::HTTP::#{method.capitalize}"

But feel this is ugly and not elegant. Is there a more rails or just a cleaner way to call that method in a dynamic way?

bubbaspaarx
  • 616
  • 4
  • 15

1 Answers1

0

Why you can't just do something like this? Net::HTTP.public_send(method.capitalize)

valduane
  • 36
  • 4
  • Nice. A neater alternative for sure. Had forgotten about ‘public_send’ – bubbaspaarx Apr 02 '23 at 19:02
  • Actually. I just tried this and it doesn't work. Unfortunately you get the error NoMethodError: undefined method `Post' for Net::HTTP:Class as we are actually trying to call the Post/Delete/Get classes which aren't methods of the HTTP class hence the :: namespace tetradot – bubbaspaarx Apr 02 '23 at 22:34
  • Sorry, my mistake. You don't need to use capitalize method: Net::HTTP.public_send(method), where method can be get, post, etc. Don't forget that this methods requires host and params – valduane Apr 05 '23 at 10:40