【发布时间】:2012-11-10 23:44:44
【问题描述】:
我有一个类似于this one 的问题。我正在编写一个具有插件系统的应用程序。有一个 Addon mixin 模块,它会检测何时包含并自动注册新的插件:
module Addon
def self.included(receiver)
addon = receiver.new # Create an instance of the addon
(snip) # Other stuff to register the addon
addon.on_register # Tell the instance it was registered
end
end
这是一个如何使用 mixin 的示例:
class MyAddon
def on_register
puts "My addon was registered"
end
include Addon # ** note that this is at the end of the class **
end
如上所述,此实现要求包含位于类的底部。否则 on_register 不会在 self.included 被调用时定义。
我担心插件开发人员可能会不小心将包含放在顶部,导致插件无法工作。或者可能有一个派生类或在 MyAddon 类被包含后会扩展它的东西。
有没有更好的方法来解决这个问题?
【问题讨论】: