2011-02-09 105 views
2

的實例方法有一個在下面的代碼紅寶石:使用模塊包括

initshared.rb 
module InitShared 
    def init_shared 
    @shared_obj = "foobar" 
    end 
end 

myclass.rb

class MyClass 
    def initialize() 
    end 
    def init 
    file_name = Dir.pwd+"/initshared.rb" 
    if File.file?(file_name) 
     require file_name 
     include InitShared 
     if self.respond_to?'init_shared' 
     init_shared 
     puts @shared_obj 
     end 
    end 
    end 
end 

的,因爲裏面的方法其包括InitShared不到風度的工作。

我想檢查文件,然後包含模塊,然後訪問該模塊中的變量。

+1

你不需要一個空的`initialize`方法。 – 2011-02-09 22:15:59

回答

0
module InitShared 
    def init_shared 
    @shared_obj = "foobar" 
    end 
end 

class MyClass 
    def init 
    if true 
     self.class.send(:include, InitShared) 

     if self.respond_to?'init_shared' 
     init_shared 
     puts @shared_obj 
     end 
    end 
    end 
end 

MyClass.new.init 

:include是一個私有類方法,因此您不能在實例級方法中調用它。另一種解決辦法,如果你希望包括模塊,只對特定的情況下,你可以更換符合:包括與該行:

# Ruby 1.9.2 
self.singleton_class.send(:include, InitShared) 

# Ruby 1.8.x 
singleton_class = class << self; self; end 
singleton_class.send(:include, InitShared) 
9

而不是使用Samnang的

singleton_class.send(:include, InitShared) 

你也可以使用

extend InitShared 

它也是一樣的,但版本無關。它只會將模塊包含到對象自己的單例類中。