The Mystery Behind Ruby Require and Load Paths

Ruby require used to annoy the hell out of me.

Because back then I didn’t know how to use it, or what exactly it does.

I knew that I need to ‘require’ in order to use custom Classes I’ve created. But
what to put in the ‘require …’, has always been trial and error for me.

Basically, ‘require’ takes in a param which contains the path to your custom
class(es) that is stored in a .rb file.

So, if I have lib/file_parser/bot.rb which contains FileParser::Bot and I want
to use it in any of my other ruby scripts, I would do a:

require ‘file_parser/bot’.

Think of it as:

require ‘[lib/]file_parser/bot[.rb]’

But wait, why do I not need to parse it in the full path?

Good question.

Well, in Ruby or Rails specifically, there’s a list of load_paths in which the
environment will looks for any of your required files.

To find out your list of default load_paths in ruby, you could:

=> ["..."]

For rails, its just a simple

$ rails console
= > ["..."]

Remember why sometimes you see answers on Stackoverflow asking you to inject your own custom load_paths into your
rails project?

Yup. Thanks why.