From: Jeff Rose Date: 2006-05-23T04:03:43+09:00 Subject: Re: initializing instance variables in a module Well, it took a while but I found the answer. This is done in ActiveRecord to wrap a possible setup method in the unit tests for auto-instrumentation of fixtures. Once I knew what to look for, however, I found an old post by Florian Gross that lays out the exact answer nicely: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/129834 For educational purposes though, I'll explain a few things I found... 1) The append_features method is deprecated, and the included method is now the preferred callback. This method is called when a module is included, and it is passed the module that has done the including. 2) There is another callback, method_added, which is a meta-class method that is called every time a new method is defined for its class, and the symbol for the method name is passed. So, the trick is to add a custom method_added method to the meta-class of the class that does the including by extending it in the included callback. The custom method_added needs to redefine initialize after it is added so that it does the custom setup, then calls the original. Phew... Too bad we can't just have another callback that lets us do this easily. Maybe that feels too much like multiple inheritance or something? module Foo def module_initialize @myvar = Hash.new {|k,v| k[v] = []} end def bar(key) @mybar[key] end end Isn't this a common thing to want? -Jeff Jeff Rose wrote: > Have a module: > > Module Foo > def add_stuff(key, stuff) > @foo_the_stuff[key] = stuff > end > end > > class Bar > include Foo > end > > Is there a standard or correct way to initialize @foo_the_stuff in this > example? Should the add_stuff method check whether the variable has > been initialized every time, or should this be done by implementing a > callback like append_features or included? (That's how I'd want to do > it, but it's not clear which or how...) > > Thanks, > Jeff > >