문제
매개변수를 login
메서드를 사용하고 해당 매개변수를 기반으로 기본 URI를 전환하고 싶습니다.
다음과 같습니다:
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
...
메서드에서 호출할 때 기본 URI가 설정되지 않습니다. 어떻게 작동하게 합니까?
해결책
HTTP파티에서는 base_uri
는 수업 방법 내부 옵션 해시를 설정합니다.사용자 정의 클래스 메소드 내에서 동적으로 변경하려면 login
그냥 메소드로 호출할 수 있습니다(변수인 것처럼 할당하지 않음).
예를 들어 위의 코드를 변경하면 다음과 같이 설정되어야 합니다. base_uri
예상대로 :
...
case game_name
when "game1"
# call it as a method
self.base_uri "http://game1"
...
도움이 되길 바랍니다.
다른 팁
아직 논평할 수 없으므로 여기에 Estanislau Trepat의 답변에 대한 확장이 있습니다.
설정하려면 base_uri
~을 위한 너의 모든 통화, 해당 클래스 메소드를 호출하십시오.
self.base_uri "http://api.yourdomain.com"
보내는 방법을 원하시면 다른 URI에 대한 몇 번의 호출 상태 오류(원래 URI로 다시 전환하는 것을 잊어버린 경우)를 방지하려면 다음 도우미를 사용할 수 있습니다.
def self.for_uri(uri)
current_uri = self.base_uri
self.base_uri uri
yield
self.base_uri current_uri
end
위의 도우미를 사용하면 다음과 같이 다른 URI에 대한 특정 호출을 수행할 수 있습니다.
for_uri('https://api.anotheruri.com') do
# your httparty calls to another URI
end
이 질문을 처음 받았을 때 구현되었는지는 확실하지 않지만 설정하거나 재정의하려는 경우 :base_uri
요청별 또는 인스턴스별로 HTTParty 요청 메서드(:get, :post 등) 옵션을 수락 클래스 옵션을 무시합니다.
따라서 OP의 예에서는 다음과 같이 보일 수 있습니다.
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
다른 답변 중 일부에서 제안한 것처럼 클래스 메서드를 동적으로 호출하면 base_uri가 변경됩니다. 모두 아마도 당신이 원하는 것이 아닐 수도 있습니다.확실히 스레드로부터 안전하지 않습니다.