2010-04-22 90 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