ruby picture

RCR 170: 'require' load path relative to the currently executing file

Submitted by legacy (Tue Nov 25 21:11:22 UTC 2003)

Abstract

This is a legacy RCR from Ruby Garden, submitted by laza. Matz has declared these RCRs obsolete, and asked that their authors resubmit them in the new format.

I propose that 'require' loads files relative to the directory of the current file.

Ruby's 'require' cannot load files in the same directory or subdirectories as the executing source file. In other programming languages (Java, C, C++) that is commonly used. Note that this is different from the current woriking directory.

Could we have:


    
    require_local  'file_in_the_same_dir'
or
    

    
    require 'file_in_the_same_dir', :local=>true

    

If we allow 'require' to load relative to the current source file, then we can just download and expand a .tgz and run, without a need to either install it or change the working directory. Also, we could use many multi-file projects without installing them into site_ruby/ or expanding $LOAD_PATH ad infinitum.

Why Patching Is Not Good Enough:

I do not want to add the directory of the currenty executing file to the library path because that would apply to all the other files, including standard library (e.g. I usually have 'utils.rb' in every project, and that would make a confusion if I tried to use two projects, or if an installed library also has 'utils').


    
    $LOAD_PATH 

Another solution is to prepend the current file's directory before every 'require', which is too verbose, repetative, and error prone (think symlinks).

    

I would also like to ask why this is NOT a standard feature of 'require'.
    require 'pathname'
    dir = Pathname.new(File.expand_path(__FILE__)).realpath
    require File.join(dir, 'utils' )   # UGLY

  

Problem

(RCR imported from old format)

Proposal

Analysis

(RCR imported from old format)

Implementation

(RCR imported from old format)
ruby picture
Comments Current voting

Re: 'require' load path relative to the currently executing file (laza, 2003-11-25 16:52:18)

HTML parser for submitting messages is broken, so the following lines are missing from the previous message (under Why Patching Is Not Good Enough):

    $LOAD_PATH <&amp;lt;File.dirname($0)         # BAD, does not work for libs<br />
    $LOAD_PATH <&amp;lt;File.dirname(__FILE__)   # Also BAD, huge LOAD_PATH<br />


Strongly opposed 0
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .