Simplifying Library Requires With $LOAD_PATH

Posted Posted by Samuel Mullen in Blog     Comments No comments
Oct
26

When creating scripts or libraries which load custom libraries or modules in the past, I’ve generally loaded them in the following manner:

require File.join(File.dirname(__FILE__), "lib/foo")
require File.join(File.dirname(__FILE__), "lib/bar")
require File.join(File.dirname(__FILE__), "lib/baz")

This loads libraries by calling each of them with their absolute path. “File.dirname” gets the directory name for the current file (__FILE__). And “File.join” joins that directory name to “lib/xxx”.

Loading libraries in this way isn’t the DRYest way of doing things, so I was happy when I ran across this in the Watchr source code:

$LOAD_PATH.unshift(File.dirname(__FILE__))

$LOAD_PATH is a global array variable holding all the paths from which ruby loads libraries. Ruby searches for libraries proceeding from the path in element 0 to the path in the last element until it finds the requested library.

The above snippet of code from Watchr places the current path at the front of the load path (unshift). Now, all following “require”s will look there first and then proceed normally through the standard paths.

So now, rather than specifically calling each library with an absolute path, I can use the following:

$LOAD_PATH.unshift(File.dirname(__FILE__))

require ‘foo’
require ‘bar’
require ‘baz’

Post comment

about databasically

We live and work in Kansas City, USA.

We're passionate about helping small businesses succeed and want to help you use technology to get more done.

From server, desktop, network management to programming custom web applications in Ruby on Rails, we're here to lend a hand.

Contact us if you have any questions!