是否有任何干净的方法来初始化模块中的实例变量,以用作Mixin?例如,我有以下几点:初始化Mixins中的实例变量
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
而不是必须重复确保东西正确初始化。但是,从我可以告诉这是不可能的。除了在Example
中添加initialize_me
方法并从扩展类中调用initialize_me
之外,有什么方法可以解决这个问题吗?我确实看到了this example,但是我没有办法只为了达到这个目的而将它们修改成Class
。
非常好,谢谢 - 我想知道为什么我没有看到这个方法提到任何地方,即使有一百万篇关于它的文章。 –
不幸的是,这看起来不起作用 - 引用'@ example_ivar'然后返回为'nil'。 –
啊,我明白了,谢谢 - 但是如果这个类已经指定了一个'initialize'方法就会引发问题,对吧? –