I am trying to pass a parameter to a login
method and I want to switch the base uri based on that parameter.
Like so:
class Managementdb
include HTTParty
def self.login(game_name)
case game_name
when "game1"
self.base_uri = "http://game1"
when "game2"
self.base_uri = "http://game2"
when "game3"
self.base_uri = "http://game3"
end
response = self.get("/login")
if response.success?
@authToken = response["authToken"]
else
# this just raises the net/http response that was raised
raise response.response
end
end
...
Base uri does not set when I call it from a method, how do I get that to work?
In HTTParty, base_uri is a class method which sets an internal options hash. To dynamically change it from within your custom class method login you can just call it as a method (not assigning it as if it was a variable).
In HTTParty, base_uri
is a class method which sets an internal options hash. To dynamically change it from within your custom class method login
you can just call it as a method (not assigning it as if it was a variable).
For example, changing your code above, this should set base_uri
as you expect:
...
case game_name
when "game1"
# call it as a method
self.base_uri "http://game1"
...
Hope it helps.
I can’t comment yet, so here’s an extension to Estanislau Trepat’s answer.
To set the base_uri
for all your calls, call the according class method:
self.base_uri "http://api.yourdomain.com"
If you want to have a way of sending only a few calls to a different URI and avoid state errors (forgetting to switch back to the original URI) you could use the following helper:
def self.for_uri(uri)
current_uri = self.base_uri
self.base_uri uri
yield
self.base_uri current_uri
end
With the above helper, you can make specific calls to other URIs like the following:
for_uri('https://api.anotheruri.com') do
# your httparty calls to another URI
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With