0

I have the name of a test class (as a string), eg."Reports::SalesReportTest". Without loading all the test files into memory, how can I find out which file Ruby would have loaded for this test-class to work?

To rephrase, is there a function which takes a class/module name (as a string), and returns the file-path that needs to be loaded for the class/module to work?

Saurabh Nanda
  • 6,373
  • 5
  • 31
  • 60

2 Answers2

0

You can't. First, a class definition can span several files. Secondly, a class can be created dynamically, for instance using eval.

If you know that the application is always written in a style that each class is fully defined in one and only one file, and that each definition follows certain style rules (for instance, each class CLASSNAME starts on a line of its own) you could read all the files in your application directory and scan for the class definition. Don't forget that there might be lines commented out with =begin and =end, which you will have to ignore.

user1934428
  • 19,864
  • 7
  • 42
  • 87
0

Given that you are using rails you could determine where it anticipates the file being (or at least where rails will look) but that does not actually mean it exists. For Example:

class_name = "Reports::SalesReportTest".underscore
potential_paths = ActiveSupport::Dependencies.autoload_paths.map do |path| 
   File.join(path.to_s,"#{class_name}.rb")
end

That will list all the locations for which rails will try and load the file from.

If you want to know that the file exists then you can ask ruby that too:

class_name = "Reports::SalesReportTest".underscore
loadable_paths = ActiveSupport::Dependencies.autoload_paths.map do |path| 
   File.exist?(File.join(path.to_s,"#{class_name}.rb"))
end
engineersmnky
  • 25,495
  • 2
  • 36
  • 52