From: Robert Dober Date: 2008-07-23T05:08:19+09:00 Subject: Re: simple module for "count my instances" behaviour On Tue, Jul 22, 2008 at 8:07 PM, ara.t.howard wrote: Maybe there is a way to leave Class alone ;) This will track instances for all ancestors of InstanceTracker. module InstanceTracker # Define a block that defines the included inclusion = proc { | by_module | singleton = class << by_module; self end unless Class === by_module then singleton.send :define_method, :included, &inclusion return end by_module.instance_variable_set "@__instances__", [] singleton.send :define_method, :inherited, &inclusion singleton.module_eval do def new *args, &blk o = allocate o.send( :initialize, *args, &blk ) @__instances__ << o o end def instances; @__instances__ end end } # Define included in base module class << self; self end. send :define_method, :included, &inclusion end # module InstanceTracker M2 = Module::new { include InstanceTracker } class A include M2 end B = Class::new A do def initialize; 42 end end A::new B::new A::new p A.instances p B.instance ---------------------------------- One could take special care of classes that define a custom new, but that would make the code too complicated for the demonstrational purpose I feel. HTH Robert -- http://ruby-smalltalk.blogspot.com/ There's no one thing that's true. It's all true. -- Ernest Hemingway