ruby: use module include in instance method of class

时间:2023-01-15 18:47:05

Have a look at the code below

看看下面的代码吧

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

myclass.rb

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

The include InitShared dosn't work since its inside the method .

包含InitShared dosn不能工作,因为它在方法内部。

I want to check for the file and then include the module and then access the variables in that module.

我要检查文件,然后包含模块,然后访问模块中的变量。

2 个解决方案

#1


9  

Instead of using Samnang's

而不是使用Samnang的

singleton_class.send(:include, InitShared)

you can also use

您还可以使用

extend InitShared

It does the same, but is version independent. It will include the module only into the objects own singleton class.

它做同样的事情,但是是独立于版本的。它将只将模块包含到对象自己的单例类中。

#2


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 is a private class method, so you can't call it in instance level method. Another solution if you want to include that module only for specific instance you can replace the line with :include with this line:

:include是一个私有类方法,因此不能在实例级方法中调用它。另一种解决方案是,如果你想只针对特定的实例包含该模块,你可以用: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)

#1


9  

Instead of using Samnang's

而不是使用Samnang的

singleton_class.send(:include, InitShared)

you can also use

您还可以使用

extend InitShared

It does the same, but is version independent. It will include the module only into the objects own singleton class.

它做同样的事情,但是是独立于版本的。它将只将模块包含到对象自己的单例类中。

#2


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 is a private class method, so you can't call it in instance level method. Another solution if you want to include that module only for specific instance you can replace the line with :include with this line:

:include是一个私有类方法,因此不能在实例级方法中调用它。另一种解决方案是,如果你想只针对特定的实例包含该模块,你可以用: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)