From: trans Date: 2009-03-20T18:50:27+09:00 Subject: [ruby-core:22971] Re: [Feature #1102] Prepend Module On Feb 7, 10:42�pm, Roger Pack wrote: > > Currently when a module is included into a classes, it is appended to the class hierarchy (ie. > the method lookup order). This of course makes sense, but there are times when it would be > useful to *prepend* the module. For example: > > I suppose one [not too useful] hack at it could be something like > > class Class > � def insert_module_at_top mod > � � previous_ancestors = self.ancestors.select{|a| a.class == Module} > � � include mod > � � previous_ancestors.each{|a| include a.dup} > � end > end > > #again we have to start with a module. > > module Original > � def x; '[' + super + ']'; end > end > > class A > �include Original > end > > modulePrepend > �def x; "x"; end > end > A.insert_module_at_topPrepend > puts A.new.x > => [x] > > Perhaps what we're saying here is we wish we could "grab" methods from > classes, to be able to manipulate the hierarchy better? �This is > possible with RubyParser, since you can basically get back to the > source of the method and thus copy it around, but not afaik with 1.9 Well, that's not really the issue here. The need is to *wrap* previously defined instance methods. If every method were defined in a module (something I have suggested in the past actually) then it would not be needed. The utility comes from doing AOP-esque coding. Consider modules that can initialize values. class X end module P attr :p def initialize @p = [] super end end class X prepend P end X.new.p => [] T.