From: Martin Hart Date: 2002-12-12T10:46:29+09:00 Subject: Re: How to detect Module Inclusion for Class Instances (like Module#extend_object)? On 12/12/02, 1:08:36 AM, Joel VanderWerf wrote regarding Re: How to detect Module Inclusion for Class Instances (like Module#extend_object)?: > > Is there a way to tell that a module is being included by a class? > > Specifically I want to detect this for instances of the class in question > > - sort of like using #extend_object. > Take a look at Module#append_features. AFAICT that works for the class - but not for instances of it... irb(main):001:0> module P irb(main):002:1> def P.extend_object(o) irb(main):003:2> puts "EXTENDED" irb(main):004:2> end irb(main):005:1> irb(main):006:1* def P.append_features(o) irb(main):007:2> puts "FEATURES APPENDED" irb(main):008:2> end irb(main):009:1> end nil irb(main):010:0> class A irb(main):011:1> end nil irb(main):012:0> irb(main):013:0* a = A.new.extend(P) EXTENDED # irb(main):014:0> class B irb(main):015:1> include P irb(main):016:1> end FEATURES APPENDED B irb(main):017:0> a = B.new # irb(main):018:0> What I want is for the module "P" to do something to instances of B when they (the instances) are created - not when the class is created. In other words - all my problems would be solved if extend_object is called when an instance of B is created. However, it isn't :-) I can see a way to achieve this by using #append_features to create a B.new function which could then do the work - but this seems a bit 'arse about face' if you'll excuse the slang :-) I have a temporary work around - which is to define a Module function that creates an instance of the object, and then calls extend on it... class Factory def Factory.createB B.new.extend(P) end end ... the problem with this approach is remembering to call it. I would appreciate any further comments on this - perhaps I am doing something that I really shouldn't be trying to do? Trouble is, Ruby is so cool that it opens avenues I would not even have considered when using C++ :-) TIA Martin