Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby path management

As of Ruby 1.9 you can use require_relative to do this:

require_relative '../src/myclass'

If you need this for earlier versions you can get it from the extensions gem as per this SO comment.


Here is a slightly modified way to do it:

$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "src"))

By prepending the path to your source to $LOAD_PATH (aka $:) you don't have to supply the root etc. explicitly when you require your code i.e. require 'myclass'


The same, less noisy IMHO:

$:.unshift File.expand_path("../../src", __FILE__)
require 'myclass'

or just

require File.expand_path "../../src/myclass", __FILE__

Tested with ruby 1.8.7 and 1.9.0 on (Debian) Linux - please tell me if it works on Windows, too.

Why a simpler method (eg. 'use', 'require_relative', or sg like this) isn't built into the standard lib? UPDATE: require_relative is there since 1.9.x


Pathname(__FILE__).dirname.realpath

provides a the absolute path in a dynamic way.


Use following code to require all "rb" files in specific folder (=> Ruby 1.9):

path='../specific_folder/' # relative path from current file to required folder

Dir[File.dirname(__FILE__) + '/'+path+'*.rb'].each do |file|
  require_relative path+File.basename(file) # require all files with .rb extension in this folder
end

sris's answer is the standard approach.

Another way would be to package your code as a gem. Then rubygems will take care of making sure your library files are in your path.