Ruby path management

Miguel Fonseca picture Miguel Fonseca · May 26, 2009 · Viewed 34.5k times · Source

What is the best way to manage the require paths in a ruby program?

Let me give a basic example, consider a structure like:

\MyProgram

\MyProgram\src\myclass.rb

\MyProgram\test\mytest.rb

If in my test i use require '../src/myclass' then I can only call the test from \MyProgram\test folder, but I want to be able to call it from any path!

The solution I came up with is to define in all source files the following line:

ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(ROOT) and then always use require "#{ROOT}/src/myclass"

Is there a better way to do it?

Answer

David Tchepak picture David Tchepak · Sep 10, 2010

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.