Initializing instance variables in Mixins

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

    module Example
      def self.included(base)
        base.instance_variable_set :@example_ivar, :foo
      end
    end
    

    Edit: Note that this is setting a class instance variable. Instance variables on the instance can't be created when the module is mixed into the class, since those instances haven't been created yet. You can, though, create an initialize method in the mixin, e.g.:

    module Example
      def self.included(base)
        base.class_exec do
          def initialize
            @example_ivar = :foo
          end
        end
      end
    end
    

    There may be a way to do this while calling the including class's initialize method (anybody?). Not sure. But here's an alternative:

    class Foo
      include Example
    
      def initialize
        @foo = :bar
        after_initialize
      end
    end
    
    module Example
      def after_initialize
        @example_ivar = :foo
      end
    end
    

提交回复
热议问题