Initializing instance variables in Mixins

后端 未结 4 894
情话喂你
情话喂你 2021-02-05 21:41

Is there any clean way to initialize instance variables in a Module intended to be used as Mixin? For example, I have the following:

module Example

  def on(..         


        
4条回答
  •  無奈伤痛
    2021-02-05 22:08

    I think there may be a simpler answer to this. The module should have an initializer that initialises the variables as you normally would do. In the initializer for the class that includes the module, invoke super() to invoke the initializer in the included module. This is simply following the method dispatch rules in Ruby.

    On reflection, this will not work so well if the class including the module also has a superclass that needs to be initialised. The initializer in the module would need to accept a variable parameter list and pass this up to the superclass. It looks like a good avenue to explore though.

提交回复
热议问题