红宝石:使用模块包括

问题描述:

的实例方法有一个在下面的代码红宝石:使用模块包括

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

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) 

而不是使用Samnang的

singleton_class.send(:include, InitShared) 

你也可以使用

extend InitShared 

它也是一样的,但版本无关。它只会将模块包含到对象自己的单例类中。