I have a lot of Ruby RSpec files that start out with a line something like this:
require File.join(File.dirname(__FILE__), %w[.. spec_helper])
“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.:
require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper])
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:
require 'pathname'
require Pathname(__FILE__).ascend{|d| h=d+'spec_helper.rb'; break h if h.file?}
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#ascenditerates backwards up a file path, successively removing path elements.Pathname#+joins two path elements using the path separator character (e.g./).breakis called with an argument, causing the block to return the matching path.





