Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ruby know where to find rspec in require "rspec"

Tags:

ruby

rspec

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.

like image 495
Daniel Thompson Avatar asked Dec 15 '25 18:12

Daniel Thompson


1 Answers

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.

like image 175
Amadan Avatar answered Dec 17 '25 13:12

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!