Trans
7/11/2006 5:22:00 PM
Jonas Pfenniger wrote:
> Thanks for your help,
>
> I finally decided to create a new Module#insert method :
>
> class Module
> def insert(new_mod)
> new_mod = new_mod.dup
> old_mod = self
> mod_name = self.basename
>
> new_mod.module_eval do
> include old_mod
> end
>
> (nesting[-2] || Object).module_eval do
> remove_const mod_name
> const_set mod_name, new_mod
> end
> end
>
> # From the Facets package
> def nesting
> n = []
> name.split(/::/).inject(self){ |mod, name| c = mod.const_get(name)
> ; n << c ; c }
> return n
> end
>
> # From the Facets package
> def basename
> if name and not name.empty?
> name.gsub(/^.*::/, '')
> else
> nil #inspect.gsub('#<','').gsub('>','').sub(':', '_')
> end
> end
> end
>
>
> I know that I can have unwanted effects but in my case it is ok
> because the loading order is pretty strict.
>
> module A
> def initialize; puts "From A"; end
> end
>
> module B
> def initialize; puts "From B"; super; end
> end
>
> A.insert(B)
>
> class C
> include A
> end
>
> C.new
> #=> From B
> #=> From A
This code essentially (or at least partially succeeds at) reversing the
inclusion order of two modules. Ie.
module B; end
module A; include B; end
becomes
module B; include A; end
Are you sure you want to do that? That can have crazy effects! In fact
it's a very bad idea unless you have full control coding over these
modules, and if that's the case you wouldn't need to do it anyway. So
as I say, I'm highly suspect. Looking at exacly what this does it
appears that:
A.insert(B)
translates into
Bp = B.dup
module Bp
include A
end
remove_const A
A = Bp
Why do you need this?
T.