2010-04-22 87 views
5

如何在Ruby中调用包含类的方法?看下面的例子。这工作,但它不是我想要的: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的base_uri。

require 'httparty' 

module MyModule 
    class MyClass 
    include HTTParty 

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

    end 
end 

回答

7

按照HTTParty source codebase_uri是一个类方法。 所以,你会需要调用该方法的类上下文

module MyModule 
    class MyClass 
    include HTTParty 

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

    end 
end 

要注意的是这种解决方案可能不是线程安全的,这取决于你如何使用你的库。

+0

你可以在线程安全问题上投入更多的信息吗?在轨道上的红宝石我们有多个进程。在这种情况下安全吗?两个进程可以同时更改类base_uri。这是如何运作的? – user566245 2013-07-31 01:38:13