tags:

views:

25

answers:

1

Hello, i would like to load modules dynamically and execute a method for each module loaded: The modules are in a directory called modules/

modules/ModA.rb

module ModA 
 def run 
   puts "module A"
  end 
end

modules/ModB.rb

module ModB 
 def run 
   puts "module B"
  end 
end

Main.rb

class Main 
  def start
    Dir.glob("modules/*.rb") do |module_file|
    load(module_file)
    # How to store modules in a list and call <Module>::run() ?
    end
  end
end


a = Main.new
a.start

So After loading modules, i would like to call run() of each modules. How can this be done ?

Thanks you.

+1  A: 

You will not be able to call the run method inside your module. To do so, write:

module ModA 
 def self.run 
   puts "module A"
  end 
end

And so on. After that, do something like this:

class Main 
  def start
    @modules = []
    Dir.glob("modules/*.rb") do |module_file|
        load(module_file)
        @modules << Kernel.const_get(File.basename(module_file, ".rb"))
        @modules.last.run
    end
  end
end

a = Main.new
a.start
floatless
thanks for this clean code, i understood how it works and i'm able to do what i wanted. Thanks
Enhancer