Why can't I require a file in the parent directory in ruby?

Jeremy Smith picture Jeremy Smith · Jul 19, 2011 · Viewed 8.4k times · Source

Note that I am not using Rails. I have a directory structure like:

foo/
bar/
base_classes/
base_classes.rb

base_classes.rb:

 Dir.glob(File.expand_path(File.join("base_classes/config/constants", "*.rb"))) { |file| require file}
 Dir.glob(File.expand_path(File.join("base_classes", "*.rb"))) { |file| require file}

when I am in this root directory

>> require 'base_classes' #=> true
>> Card.load!
[stuff happens]

But when I am in foo/ and do either of the following:

>> require '../base_classes' #=> true
>> require File.expand_path("../base_classes.rb") #=> true
>> require File.expand_path("../base_classes") #=> true
>> Card.load!
>> NameError: uninitialized constant Card

Answer

Denis de Bernardy picture Denis de Bernardy · Jul 19, 2011

require is based on the file that gets called, which usually means config.ru. You need require_relative (which is based on the current file), or an absolute path.