DISQUS

Virtuous Code: Double-Load Guards in Ruby

  • R. Konstantin Haase · 2 months ago
    I disagree. Doing require File.expand_path is way to ugly. Just setup you $LOAD_PATH correctly and you will not encounter any of such problems. Treat your code as if it was a library.
  • avdi · 2 months ago
    Konstantin, thanks for your comment. Setting up $LOAD_PATH is essential and I make sure to add the current project to the load path in all but the smallest of projects.

    However, there are always a few files where relative requires can't be avoided. For instance, it is conventional to set up unit test/spec files so that they can be run standalone. In order for this to work each test file has to start out by requiring a test_helper.rb or a spec_helper.rb which then sets up $LOAD_PATH, requires additional libraries, etc. Because this test helper is the first thing to be loaded and can't rely on anything else to be configured, it has to be loaded with a relative path.

    This is where I see the most double-loads occurring, because when all of the tests are run together they each require the test helper file, often with differing relative paths. Using expand_path is a way to ensure that files that must loaded relatively are required in a consistent way.

    I may update the post to make it clear that I'm not suggesting you use relative requires throughout a project.
  • R. Konstantin Haase · 2 months ago
    You're right. But specs/tests is about the only place I do so myself.
  • François Beausoleil · 2 months ago
    Why not use Ruby 1.9, which fixed the problem by storing the expanded path in the require table? http://eigenclass.org/hiki/Changes+in+Ruby+1.9#l25
  • Mike Subelsky · 2 weeks ago
    Another awesome post Avdi! We were having some hard-to-trace double constant definitions and using this code in my Rails pre-initializer TOTALLY surfaced them. Thanks!