Come cambiare base_uri con httparty
Domanda
Sto cercando di passare un parametro a un metodo login
e voglio cambiare l'URI di base in base a quel parametro.
Come così:
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 non imposta quando lo chiamo da un metodo, come posso ottenere quello per lavorare?
Soluzione
In httparty, base_uri
è un metodo di classe che imposta un'opzione interna hash.Per modificarlo dinamicamente dall'interno del metodo di classe personalizzato login
puoi chiamarlo come metodo (non assegnandolo come se fosse una variabile).
Ad esempio, modificando il codice sopra, questo dovrebbe impostare base_uri
come ti aspetti:
.
...
case game_name
when "game1"
# call it as a method
self.base_uri "http://game1"
...
Spero che aiuti.
Altri suggerimenti
Non posso ancora commentare, quindi ecco un'estensione della risposta di Estanislau Trepat.
Per impostare il base_uri
per Tutte le chiamate , chiama il metodo di base:
.
self.base_uri "http://api.yourdomain.com"
Se si desidera avere un modo di inviare solo poche chiamate a un diverso URI ed evitare errori di stato (dimenticando di tornare all'URI originale) È possibile utilizzare il seguente helper:
.def self.for_uri(uri)
current_uri = self.base_uri
self.base_uri uri
yield
self.base_uri current_uri
end
.
Con l'helper sopra, è possibile effettuare chiamate specifiche ad altri URI come quanto segue:
for_uri('https://api.anotheruri.com') do
# your httparty calls to another URI
end
. Non sono certo che è stato implementato quando è stata applicata questa domanda, ma se si desidera impostare o sovrascrivere :base_uri
su base per richiesta o per-istanza, i metodi di richiesta di httparty (: ottenere ,: post, ecc.) Accetta le opzioni per sovrascrivere le opzioni di classe.
Quindi per l'esempio dell'OP, potrebbe sembrare qualcosa del genere:
class Managementdb
include HTTParty
# If you wanted a default, class-level base_uri, set it here:
base_uri "http://games"
def self.login(game_name)
base_uri =
case game_name
when "game1" then "http://game1"
when "game2" then "http://game2"
when "game3" then "http://game3"
end
# To override base_uri for an individual request, pass
# it as an option:
response = get "/login", base_uri: base_uri
# ...
end
end
.
Chiamare dinamicamente il metodo di classe, come suggerito in alcune delle altre risposte, modifica la base_uri per tutte le richieste , che probabilmente non è quello che vuoi.Non è certamente sicuro.