1

A general question about require in Ruby.
My understanding of Ruby's require is that the file specified is only loaded once but can be executed multiple times. Is this correct?
I have a set of Rspec tests in different files which all require the same file logger.rb. It doesn't seem like the methods I call in the required file are executed in every spec.
Here is some of the code I wrote in logger.rb, it first cleans up the temp dir an then creates a logger.

tmpdir = Dir.tmpdir
diagnostics_directory = File.join(tmpdir, LibertyBuildpack::Diagnostics::DIAGNOSTICS_DIRECTORY)
FileUtils.rm_rf diagnostics_directory
raise 'Failed to create logger' if LibertyBuildpack::Diagnostics::LoggerFactory.create_logger(tmpdir).nil?

I'd like this to happen in every spec. Is that because the tests are within the same module or did I misunderstand how require works.

chibi03
  • 121
  • 1
  • 9

1 Answers1

2

There is still a great many ifs, as you do not show the code requiring your file, but I think I have understood some of the misunderstandings you had :-)

Your statement 'The file specified is only loaded once but can be executed multiple times.' is basically the opposite of what is true. If a file is to have any effect on a ruby program it will have to be 'executed', it may just happen sometimes that one of the executed methods defines other methods or classes. All statements in a file will be executed once when loaded, but you may load a file multiple times. If you require a file it will only be loaded if it has not been done so already, so as with method definitions your 'static' method calls will only be executed once.

If you want to execute things multiple times you should either load the file (which is usually inefficient since all the compiling will have to be done again) or you require a file with a method definition in it (def ... end) and you call the method multiple times (with possibly varying parameters). The latter is the usual way, as compiling will only have to take place once this way.

Patru
  • 4,481
  • 2
  • 32
  • 42