2010-07-29 110 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| 
...