Smart Requires in Ruby

I have a lot of Ruby RSpec files that start out with a line something like this:

“This is boilerplate” thought I one day, “my editor should insert this line for me!” But there’s a problem: the line must change depending on how deep in the directory hierarchy the file is found. E.g.:

This is Ruby, though. Surely there is a concise way to dynamically locate a file in a parent directory? As it turns out, there is. Here’s my solution:

OK, it’s two lines instead of one. But the advantage is, now I can insert those two lines into my standard editor template for *_spec.rb files. And it’ll Just Work so long as there is a spec_helper.rb somewhere in the file’s parent directories.

How it works:

  • Pathname#ascend iterates backwards up a file path, successively removing path elements.
  • Pathname#+ joins two path elements using the path separator character (e.g. /).
  • break is called with an argument, causing the block to return the matching path.