Initializing instance variables in Mixins

后端 未结 4 855
情话喂你
情话喂你 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:15

    Perhaps this is a little hacky, but you can use prepend to get the desired behavior:

    module Foo
      def initialize(*args)
        @instance_var = []
        super
      end
    end
    
    class A
      prepend Foo
    end
    

    Here is the output from the console:

    2.1.1 :011 > A.new
     => #
    

提交回复
热议问题