In Ruby I can require another file using a relative path with require_relative "file.rb"
But how come I'm able to write require 'rspec' in a random Ruby file and have it know exactly which file I'm referring to?
I understand (after reading this post) that in rails require is working with $LOAD_PATH to find the file path, but I'm not seeing how it works in some arbitrary directory.
This post explains it in detail. Here's the important bits:
To help you use the code inside of your gems, RubyGems overrides Ruby’s require method. (It does this in core_ext/kernel_require.rb). The comment is pretty clear:
## # When RubyGems is required, Kernel#require is replaced with our own which # is capable of loading gems on demand. # # When you call <tt>require 'x'</tt>, this is what happens: # * If the file can be loaded from the existing Ruby loadpath, it # is. # * Otherwise, installed gems are searched for a file that matches. # If it's found in gem 'y', that gem is activated (added to the # loadpath). #
The rest of the post walks us through the require process step by step, looking through the code; but the gist of it is, if original require (through $LOAD_PATH) fails, it will scan the specification files of all installed gems and see if your require is supposed to work with it; if so, it activates (adds to $LOAD_PATH) that gem and also all gems that it depends on; finally it will re-invoke the original require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With