never_had_a_name
never_had_a_name

Reputation: 93216

Require a module file and interact with its module?

In a folder I have random module files.

eg. "user.rb" that contains "module User", "customer.rb" that contains "module Customer" and so on.

I want to require all files and print out all module methods.

Here is my current code:

  @@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

How could i do this?

Thanks

Upvotes: 1

Views: 208

Answers (1)

Daniel O&#39;Hara
Daniel O&#39;Hara

Reputation: 13438

You can use the Kernel#const_get method to get every module by its name, so:

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

Upvotes: 3

Related Questions