开发者

How to load modules with an iteration and execute a method in RUBY

开发者 https://www.devze.com 2023-01-10 07:56 出处:网络
i would like to load modules dynamically and execute a method for each module loaded: The modules are in a directory called modules/

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
0

精彩评论

暂无评论...
验证码 换一张
取 消