How does Ruby know where to find a required file?

11,243

Solution 1

When you start your rails app it runs config/boot.rb which calls Rails::Initializer.set_load_path and thatsets up the $LOAD_PATH.

Ruby uses that list of directories to find the files specified on a require line. If you give it an absolute path like require '/home/lolindrath/ruby/lib.rb' it will skip that search.

This is roughly analogous to #include <stdlib.h> in C/C++ where it searches the include path you give the compiler to find that header file.

Solution 2

I believe because your paths are set up in your /config/environment.rb file:

require File.join(File.dirname(__FILE__), 'boot')

Solution 3

Sure. In /config/boot.rb (called in environment.rb) the RAILS_ROOT is set up as so:

RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)

Which allows you to require things from the root I believe. Hope that's the answer anyway!

Share:
11,243
eric2323223
Author by

eric2323223

Updated on June 04, 2022

Comments

  • eric2323223
    eric2323223 almost 2 years

    Here is one more newbie question:

    require 'tasks/rails'
    

    I saw this line in Rakefile in the root path of every rails project. I guess this line is used to require vendor/rails/railties/lib/tasks/rails.rb to get all rake tasks loaded:

    $VERBOSE = nil
    # Load Rails rakefile extensions
    Dir["#{File.dirname(__FILE__)}/*.rake"].each { |ext| load ext }
    # Load any custom rakefile extensions
    Dir["#{RAILS_ROOT}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
    Dir["#{RAILS_ROOT}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
    

    My question is why only 'tasks/rails' is specified for the require method, but not the full path of the file?

    Thanks in advance.

  • eric2323223
    eric2323223 over 15 years
    I don't understand, could you please be more specific?
  • Lolindrath
    Lolindrath over 15 years
    This gets the filename of the script currently running, it gets the directory that file lives in using File.dirname and then appends a new file to it (i.e. requiring a file that you know is in the same directory but not in the $LOAD_PATH). Then File.join safely makes the new filename.
  • Rory O'Kane
    Rory O'Kane about 12 years
    Working link to Rails 2.3’s set_load_path. (Line number may change, but file probably won’t.) (I don’t know where Rails 3 puts that same code.)