From: Hugh Sasse Staff Elec Eng Date: 2002-02-05T00:38:10+09:00 Subject: Re: Mixins and accessing earlier definitions. On Tue, 5 Feb 2002, ts wrote: > >>>>> "H" == Hugh Sasse Staff Elec Eng writes: > > H> subclass in between including successive modules. I think this is > H> because included modules appear as superclasses of the class that > H> includes them. [...] > Now if you include the module B, this will give > > class A; include B; end > > A < [B] < Object > > [B] is a proxy class to the module B > > When an object of A call a method, ruby will look in A, then B, etc OK. > > H> If a module is intended to {override or add} a method, how should this > H> be done in idiomatic Ruby? Obviously my way of thinkig is wrong :-). > H> I think using alias in the case where a method is added could be a > H> problem, because the old method to be aliased will not exist. > > Well, you don't have this problem with 'include', for example if you want > to redefine a method of Object (like to_s) for A, but using a module you > just write > > module B > def to_s > "B::" + super When I tried this I didn't seem to need "B::". > end > end > class A > include B > end > > A.new.to_s > > When #to_s is invoked, ruby first search in A, then in B where it find it OK, but in the override case, where A already has a to_s method, this won't work.... > The call to #super in B, will force ruby to continue the search and call What I wanted to do was to access the original definition before I overrode it. I need something that goes down rather than up the tree to do this with modules. I think it will have to be alias, unless "there is a better way to do it" :-). > the original method of Object > > H> Also, several successive overrides could be a problem using alias. > > It's best to test if a method exist before trying to define un alias, > otherwise you can create infinite loop. so it looks like this is the way to go. Maybe I should step back a bit, to explain my purpose: I am trying to rewrite some code to make it more flexible. I have one class with many properties that I would like to change: they will be present or absent at the moment. Three such properties could give me 8 subclasses, which is daft. So I'm trying to have the class be extended with modules. I want the new (with-module-X) class to have its methods overridden somehow by the module. Thus I can use both classes in the same code [responds_to?, static typing debate, ...]. I fulfil the same contract, but outsource some jobs to modules. Deos this clarify where I am headed? > > > Guy Decoux > Hugh.