From: Hugh Sasse Staff Elec Eng Date: 2002-02-05T02:53:21+09:00 Subject: Re: Mixins and accessing earlier definitions. On Tue, 5 Feb 2002, ts wrote: > >>>>> "H" == Hugh Sasse Staff Elec Eng writes: > > H> Yes, that is what I tried -- it makes no difference, really, because it > H> still ends up as a superclass... > > Try this > > pigeon% cat b.rb > #!/usr/bin/ruby > module B > def self.append_features(kl) # OK this gets called when included in another module/class.. > klass = self > kl.class_eval do # In that class... > if method_defined?(:aa) && !method_defined?("_aa_#{klass}_") > alias_method "_aa_#{klass}_", :aa # rename the method to reflect where it now is... > remove_method :aa # and remove the original so the new aa will be found... > end > end > super > end # The new aa ia this: > def aa > puts "B::aa" # call the old one... > _aa_B_ if respond_to? :_aa_B_ > end > end > > def aa > puts "object" > end > > class A > def aa > puts "A::aa" > # super > end > > include B > end > > A.new.aa > pigeon% > > H> I don't think it will, but I'll bear that in mind. > > To see the problem with #super, remove the comment in A#aa It loops forever, but Object.aa never gets called... because the module is interposed btween A and Object... I can't see where the loop is occurring, though. I am beginning to get the feeling that my whole approach to this problem is counter to the design of Ruby. From the exposure to Ruby's design that I have had, this suggests that my approach is wrong. Being able to create new classes by plugging code into them, redefining methods at the time of plugging in, without having to create a whole tree of subclasses would seem like a fairly structured approach..... I wondered if I needed some kind of Factory pattern for this, but looking at RubyGarden I suspect that DecoratorPattern http://www.rubygarden.org/ruby?DecoratorPattern might be more appropriate. Now, if I put the code using singleton methods and method aliases (at the end of the page) inside a module, maybe using class << self, would this work... I suspect not, because the module would still be the partent of my class... But if I put it inside: module B def self.append_features(kl) klass = self kl.class_eval do ... end end end can I get away with having a def inside a def? This still feels too much like an uphill struggle for idiomatic Ruby > Guy Decoux > > Hugh