我正在尝试将参数传递给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在从方法调用它时未设置,我如何获得工作?

有帮助吗?

解决方案

在httparty中,base_uri是一个类方法,它设置内部选项哈希。要从自定义类方法中动态更改它,您可以只需将其称为方法(未将其分配,就像它是变量一样)。

例如,更改上面的代码,这应该按照您期望的情况设置生成的icetagcode:

...
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
.

我不确定它是在第一次提出这个问题时实现的,但如果要在每次请求或每个实例的基础上设置或覆盖生成的世代odeTagcode,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,这可能不是您想要的。它肯定不是线程安全的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top