【问题标题】:Httparty - Dynamically setting base_uri for current instance onlyHttparty - 仅为当前实例动态设置 base_uri
【发布时间】:2019-03-02 13:04:08
【问题描述】:

我有以下代码为所有 http 请求动态设置 base_uri。

class Managementdb
  include HTTParty

  def set_url(username)
    self.class.base_uri = "https://#{username}.example.com"

    # ...
  end
end

但是我发现这不仅为当前实例设置了 base_uri,还为该类的所有其他未来实例设置了 base_uri。

是否可以在方法中设置像 base_uri 这样的默认选项,但仅适用于正在调用它的当前实例?

谢谢 斯科特

【问题讨论】:

    标签: ruby httparty


    【解决方案1】:

    你可以使用block 来解决这个问题。我已经根据您的需要实现了一个。

    class Managementdb
      include HTTParty
    
      def set_url(username)
        self.class.base_uri = "https://#{username}.example.com"
    
        # ...
      end
    
      def get_userinfo
        wrapper do
          set_url(username)
          self.class.get('/info')
        end
      end
    
      def wrapper(&block)
        yield
        self.class.base_uri = nil
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 2016-01-06
      相关资源
      最近更新 更多