在Ruby中包含类的调用方法

Mad*_*bæk 5 ruby

你如何在Ruby中调用包含类的方法?请参阅下面的示例.这有效,但它不是我想要的:

require 'httparty'

module MyModule
  class MyClass
    include HTTParty
    base_uri 'http://localhost'        

    def initialize(path)
      # other code
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

这就是我想要的,但不起作用,说undefined method 'base_uri' [...].我要做的是从initialize参数动态设置httparty的base_uri.

require 'httparty'

module MyModule
  class MyClass
    include HTTParty

    def initialize(path)
      base_uri 'http://localhost'
      # other code
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

Sim*_*tti 7

根据HTTParty源代码,base_uri是一个类方法.所以你需要在类上下文中调用该方法

module MyModule
  class MyClass
    include HTTParty

    def initialize(path)
      self.class.base_uri 'http://localhost'
      # other code
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,此解决方案可能不是线程安全的,具体取决于您使用库的方式.