你如何在
Ruby中调用包含类的方法?请参阅下面的示例.这有效,但它不是我想要的:
require 'httparty' module MyModule class MyClass include HTTParty base_uri 'http://localhost' def initialize(path) # other code end end end
这就是我想要的,但不起作用,说未定义的方法’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
解决方法
根据
HTTParty source code,base_uri是一种类方法.
所以你需要在类上下文中调用该方法
所以你需要在类上下文中调用该方法
module MyModule class MyClass include HTTParty def initialize(path) self.class.base_uri 'http://localhost' # other code end end end
请注意,此解决方案可能不是线程安全的,具体取决于您使用库的方式.