动态地将模块中的方法添加到类的特定实例

Luc*_*rim 3 ruby singleton eval local-variables eigenclass

这是交易:我需要用一些方法扩展class Box的特定实例.我需要包含实时内部模块的方法,我希望Box实例能够动态地包含模块.现在我使用带有eval的钩子:

class Box
  def after_initialize
    if self.injected_module.present?
      eval("class << self; include #{self.injected_module}; end")
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

它工作得很好但是当我使用eval时我真的感觉很脏.我正在寻找类似的东西:

module_to_inject = self.injected_module
self.eigenclass.class_eval do
   include module_to_inject
end
Run Code Online (Sandbox Code Playgroud)

但是我无法让eigenclass在没有monkeypatching类的情况下运行class_eval:

class Box; def eigenclass; class << self; self; end end end
Run Code Online (Sandbox Code Playgroud)

有一种美丽(可靠)的方式让我这样做吗?

Tom*_*Tom 8

您需要将模块中的方法添加到Box动态的特定实例中的Kernel#extend方法是:

box.extend MyModule
Run Code Online (Sandbox Code Playgroud)

另外,因为动词"to inject"已经在Ruby中有意义Enumerable#inject,所以描述它的最佳动词是"扩展".