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
d开发者_运维百科ef 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.
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
精彩评论