如何使用httparty切换base_uri

Jos*_*ech 16 ruby httparty

我试图将参数传递给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

  ...
Run Code Online (Sandbox Code Playgroud)

当我从一个方法调用它时,基础uri没有设置,我该如何让它工作?

Est*_*pat 16

在HTTParty中,base_uri是一个设置内部选项哈希的类方法.要从自定义类方法中动态更改它,您login只需将其称为方法(不要将其指定为变量).

例如,更改上面的代码,应该base_uri按预期设置:

...
case game_name
  when "game1"
    # call it as a method
    self.base_uri "http://game1"
...
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • 在我的`initialize`方法中,我不得不调用`self.class.base_uri"http://example.com"`来使它工作. (20认同)
  • @hamstar,但这会更改所有实例的base_uri吗?因此,所有实例的行为都将类似于最后一个实例,对吧? (2认同)

小智 8

我还不能发表评论,所以这里是Estanislau Trepat答案的延伸.

要设置base_uri为所有来电,拨打根据类方法:

self.base_uri "http://api.yourdomain.com"
Run Code Online (Sandbox Code Playgroud)

如果您想要一种方法只发送几个调用到不同的URI并避免状态错误(忘记切换回原始URI),您可以使用以下帮助器:

def self.for_uri(uri)
  current_uri = self.base_uri
  self.base_uri uri
  yield
  self.base_uri current_uri
end
Run Code Online (Sandbox Code Playgroud)

使用上面的帮助程序,您可以对其他URI进行特定调用,如下所示:

for_uri('https://api.anotheruri.com') do
  # your httparty calls to another URI
end
Run Code Online (Sandbox Code Playgroud)


Ste*_*eve 6

我不确定第一次问这个问题时它是否已实现,但是如果您想: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
Run Code Online (Sandbox Code Playgroud)

正如其他一些答案中所建议的那样,动态调用类方法会更改所有请求的 base_uri ,这可能不是您想要的。它当然不是线程安全的。