2010-07-29 129 views
1

在一個文件夾中我有隨機模塊文件。需要一個模塊文件並與其模塊交互?

例如。包含「模塊用戶」的「user.rb」,包含「模塊客戶」的「customer.rb」等。

我想要求所有文件並打印出所有的模塊方法。

這裏是我當前的代碼:

@@data_module_methods = [] 

    # iterate through all files in the data folder 
    Dir[File.join(APP_ROOT, "data", "*.rb")].each do |file| 
    require file 
    # give me the module name from the filepath (so ./data/user.rb will give me User) 
    data_module_name = file.split("/").[](-1).split(".").[](0).capitalize 

    # ERROR: print all method names, HERE IT FAILS BECAUSE data_module_name is a string and not the module:) 
    data_module_name.instance_methods.each do |method| 
     @@data_module_methods << method 
    end 
    end 

我怎麼能這樣做?

感謝

回答

3

可以使用Kernel#const_get方法,通過它的名字讓每一個模塊,所以:

... 
Kernel.const_get(data_module_name).instance_methods.each do |method| 
...