是否有任何干净的方法来初始化模块中的实例变量以用作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
Run Code Online (Sandbox Code Playgroud)
请注意,我必须反复检查@member每个功能是否已在每个功能中正确初始化 - 这有点刺激性.我宁愿写:
module Example
def initialize
@handlers = {}
@unhandled = []
@all_handlers = []
end
# or …Run Code Online (Sandbox Code Playgroud)