From: Brian Candler Date: 2010-02-10T06:33:55+09:00 Subject: Re: Mixin module with class variables and class methods John Lane wrote: > Ok so I get that point. I've now got working code, well almost. I mix > the module into multiple classes and each gets their own instance of the > variable, which is not what I need. If everything which mixes in this module shares the same state, then you can use a module instance variable. If you want each subtree of related classes to share state, then one option is to use a class instance variable and use the class hierarchy to find where the value is held. Along the lines of: def name defined?(@name) ? @name : super end Another option is for each class to have its own @name instance variable, but for them all to refer to the same object (a Hash in your case); in self.included you initialize @name to the same as @name in the parent class, if it exists. But in your case class One and Two are unrelated but you want them to share state anyway, so I'd go with a module instance variable. This passes your test: module TestMixin @list = "a" def self.list @list end def self.included(base) puts "TestMixin included in #{base}" base.extend ClassMethods end module ClassMethods def list TestMixin.list end def class_method(str) self.list << " #{str}" puts "#{str} added for class #{self} : #{list}" end end def list TestMixin.list end def instance_method puts "the list for class #{self.class} is #{list}" end end class One include TestMixin class_method 'b' class_method 'c' end class Two include TestMixin class_method 'd' class_method 'e' end class Three < Two class_method 'f' class_method 'g' end one = One.new two = Two.new three = Three.new one.instance_method two.instance_method three.instance_method -- Posted via http://www.ruby-forum.com/.