Main Content

Where does Ruby load modules from, and how to load from current directory

Archive - Originally posted on "The Horse's Mouth" - 2015-06-03 09:42:02 - Graham Ellis

All (scripting) languages allow you to load code from other supporting source files, using keywords like use, load, source and include. In Ruby, the most common way to load other code is to require it - and if you use the require method you'll load in code from another file which will be assumed to have a .rb extension.

But where is the extra code loaded from? And - more importantly - where do you want it loaded from?

Ruby looks for code it's asked to load in the directories listed in the $LOAD_PATH special variable (also known as $:) ... taking each of the directories in turn. There's a whole discussion on this variable and manipulating it on StackOverflow - [here].

Let's take a look at where the codes loaded from on my current system:

  WomanWithCat:kingston grahamellis$ irb
  irb(main):001:0> require "pp"
  => true
  irb(main):002:0> pp $:
  ["/Library/Ruby/Site/2.0.0",
   "/Library/Ruby/Site/2.0.0/x86_64-darwin13",
   "/Library/Ruby/Site/2.0.0/universal-darwin13",
   "/Library/Ruby/Site",
  "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/vendor_ruby/2.0.0",
  "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/vendor_ruby/2.0.0/x86_64-darwin13",
     "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/vendor_ruby/2.0.0/universal-darwin13",
   "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/vendor_ruby",
   "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0",
   "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/x86_64-darwin13",
   "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/universal-darwin13"]


Any you'll note that Ruby looks first in various local (site) directories, and then into a series of directories that are supplier specific, and finally into general directories. But it does NOT include the current directory, which can be an issue when you're developing and testing code.

You could add a check of your current directory onto the top of your program:
  $:.unshift File.dirname(__FILE__)
or (for something really quick and dirty) simply be specific in the require - here's a 'complete' program:
  require "./transport"
  p (Train.new 9,40,"09:45").getCapacity

Complete source of that (and sample output!) [here]. The cluster of classes that uses [here].