Cleaning up require statements with Ruby's $: global variable

Ever run across something like the below line in helper files?

$:.unshift File.expand_path("../../lib", __FILE__)

This little trick allows you to be lazy with your require statements further down the road. This line will load onto your path your lib directory so that your downstream require statments can look like

require '/class_name'

instead of

require './lib/class_name'

Doesn’t seem like much but it does make file dependencies easier to sort out if you have a big project.

But, how does that code work? Let’s break it down.

In other words, this statment says, from the current file (FILE) go up two directories (../..) and into the lib folder. Then, make this path absolute (expand_path) and push it into the loadpath (.unshift).

To learn more, check out this helpful post.