【发布时间】:2012-09-17 03:41:08
【问题描述】:
是否有任何干净的方法来初始化要用作 Mixin 的模块中的实例变量?例如,我有以下内容:
module Example
def on(...)
@handlers ||= {}
# do something with @handlers
end
def all(...)
@all_handlers ||= []
# do something with @all_handlers
end
def unhandled(...)
@unhandled ||= []
# do something with unhandled
end
def do_something(..)
@handlers ||= {}
@unhandled ||= []
@all_handlers ||= []
# potentially do something with any of the 3 above
end
end
请注意,我必须一次又一次地检查每个 @member 是否已在每个函数中正确初始化——这有点烦人。我宁愿写:
module Example
def initialize
@handlers = {}
@unhandled = []
@all_handlers = []
end
# or
@handlers = {}
@unhandled = []
# ...
end
并且不必反复确保事物已正确初始化。但是,据我所知,这是不可能的。除了将initialize_me 方法添加到Example 并从扩展类调用initialize_me 之外,还有什么办法可以解决这个问题?我确实看到了this example,但我无法将猴子修补到Class 中来完成此操作。
【问题讨论】: