如何在Ruby中调用包含类的方法?请参见下面的示例。这是可行的,但这不是我想要的:
require 'httparty' module MyModule class MyClass include HTTParty base_uri 'http://localhost' def initialize(path) # other code end end end
这是我想要的,但不起作用,说 undefined method 'base_uri' [...] . 我要做的是从initialize参数动态地设置httparty的基URI。
undefined method 'base_uri' [...]
require 'httparty' module MyModule class MyClass include HTTParty def initialize(path) base_uri 'http://localhost' # other code end end end
根据 HTTParty source code , base_uri 是类方法。 所以您需要在类上下文上调用该方法
base_uri
module MyModule class MyClass include HTTParty def initialize(path) self.class.base_uri 'http://localhost' # other code end end end
请注意,根据您如何使用库,此解决方案可能不具有线程安全性。