Load path and require vs. require_relative

After hours and hours looking on Google for “what is load path?” and “what is require?” and “require vs. require relative”, I finally had a Eureka moment this morning when Christoph explained it to me.

This blog post is a note to myself so I will always remember what load path is and why we should use require and not require relative.

  • What is load path?

It looks like this on a ruby project:

$LOAD_PATH << File.expand_path(‘../../../lib’, __FILE__)

Load path is an array. An array where we store files paths.

We could translate “$LOAD_PATH << File.expand_path(‘../../../lib’, __FILE__)” into “starting from FILE, follow the path down ../../../lib, then return the absolute path of lib” (where your code is). 
In short: imagine load path like a bucket where all your files paths are.

When you are working on a project, you might need to get access to files and the code that is inside. How do you do that? By using require.
You only need to write “require + name of your file” and you are done! 
When you write “require + name of your file”, imagine you are making a call to load path, asking hey! Give me this file and the information inside and load path will do it.

Now you know what load path is, check; what require is, check; but what is this require_relative we see everywhere?
Well, from what I read you shouldn’t see it and use it.
Require is used to require a file, a file stored in load path. So far so good. But, when you use require_relative it is like asking to retrieve a file from a specific location and that is a bad practice. It is bad because you should require files that are in load path and not ask to retrieve files from a specific location. There are complicated explanations as to why specifically, we shouldn’t use require_relative but I leave those for later when I will work on a big ruby project and face this problem. Let’s stick to using require, it’s easier and above all, it makes sense.

Show your support

Clapping shows how much you appreciated sophie’s story.