How to Set Ruby's Load Path Externally

How to set Ruby's load path externally

See the "Ruby and Its World" chapter from The Pickaxe Book, specifically the section on environment variables. Excerpt:

RUBYLIB 
Additional search path for Ruby programs ($SAFE must be 0).
DLN_LIBRARY_PATH
Search path for dynamically loaded modules.
RUBYLIB_PREFIX
(Windows only) Mangle the RUBYLIB search path by adding this
prefix to each component.

Add $LOAD_PATH externally

RUBYLIB environment variable is a colon separated list of paths which ruby will prepend the the standard LOAD_PATH. ruby -I path on the command line is also the same as $LOAD_PATH.unshift 'path' in your code. Ruby will also process options from environment var RUBYOPT.

Requiring file outside of load path in Ruby

This was fixed using require_relative and expanding the file path using Dir.pwd:

req_path = File.expand_path(arg, Dir.pwd)
require_relative req_path

Why load file.rb works even though . is not in the load path?

See the documentation of Kernel#load clearly :

Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

In case load 'second.rb' - second.rb has been internally resolved to the absolute path /Projects/test/second.rb,as your requiring file in the directory is same as required file directory. Nothing has been searched to the directories listed in$: for your case.

Just remember another way always
- The load method looks first in the current directory for files

Linking to external files in ruby?

require "YOUR_EXTERNAL_FILE_NAME_WITHOUT_DOT_RB_EXTENSION"

For example, if you have two files, 'file0.rb' and 'file1.rb' and want to include 'file0.rb' from 'file1.rb' (and both files are in the same folder), your 'file1.rb' should have following statement:

require 'file0'

$LOAD_PATH does not include working directory?

$LOAD_PATH includes current directory in Ruby 1.8.7, but this behavior have been changed in 1.9.2. You can find possible explanations for the reasons behind this decision among answers to this question, but I think basic idea is that . in 1.8.7 stands for directory from which your code is executed and not the one where it is located. And in most cases you don't want that and . in your $LOAD_PATH is not reliable.

Using require_relative in 1.9.2 might be a good solution if you don't want to add . manually to your $LOAD_PATH everywhere. You can see here that what it does is just explicit expanding relative path. One thing to note is that it's not available in versions prior to 1.9.2 so it'll make your code incompatible with older rubies.



Related Topics



Leave a reply



Submit