views:

21

answers:

1

Is there any way, to track dynamically which classes or modules are included in required files.

a short example:

#my_module.rb
module MyCustomModule
  def foo
  end
end

#custom.rb
require 'my_module.rb'
#is here any way to track which modules are in the required 'my_module.rb' 
#without parsing the file or having some naming conventions?

The aim is, to require dynamically a bunch of files and including the contained modules in a class, regardless of how they are named.

A: 

You can use ObjectSpace to determine newly defined Modules.

#custom.rb
existing_modules = ObjectSpace.each_object(Module).to_a
require 'my_module.rb'
new_modules = ObjectSpace.each_object(Module).to_a - existing_modules
 # => [MyCustomModule]

class X
  new_modules.each{|m| include m}
end

Note: You probably want to only include the top level ones, though, so check the names for ::

Marc-André Lafortune
thx, that looks great.
Sebastian