【发布时间】:2011-07-14 17:22:04
【问题描述】:
这是交易:我需要使用一些方法来扩展 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
我是否有一种漂亮(且可靠)的方式来做到这一点?
【问题讨论】:
标签: ruby singleton eval local-variables eigenclass