这是交易:我需要使用一些方法扩展 Box 类的特定实例。我需要包含在模块中的方法,并且我希望 Box 实例能够动态地包含模块。现在我正在使用带有 eval 的钩子:
class Box
def after_initialize
if self.injected_module.present?
eval("class << self; include #{self.injected_module}; end")
end
end
end
它工作得很好,但是当我使用eval时我真的觉得很脏。我正在寻找类似的东西:
module_to_inject = self.injected_module
self.eigenclass.class_eval do
include module_to_inject
end
但我无法让 eigenclass 运行class_eval而无需像以下那样对类进行猴子补丁:
class Box; def eigenclass; class << self; self; end end end
有没有一种漂亮(可靠)的方法可以让我做到这一点?