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

4

9

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
Sweetening answered 19/7, 2011 at 20:9 Comment(0)
T
6

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.

Thinkable answered 19/7, 2011 at 20:12 Comment(2)
Shouldn't the include with expand_path work then? That creates an absolute path.Sweetening
It should, but... What does require_relative yield?Thinkable
B
5

This may be playing a part, depending on which version of ruby you're using.
Current directory removed from load path for ruby 1.9.2

I suspect your problem is this line: require '../base_classes' when in foo/.
Try require_relative '../base_classes' instead and see what happens.

This is assuming you are using ruby 1.9.2. If not, may need to dig deeper. You should tag the question or mention in it (or both, preferrably) which version of ruby you're running.

Bonanza answered 19/7, 2011 at 20:36 Comment(0)
P
1

All that was needed was to use a single dot instead of two dots.

Based on the given example code:

require File.expand_path("./base_classes.rb")
Pebbly answered 19/9, 2011 at 12:40 Comment(0)
S
0

The issue was actually inside of base_classes.rb, I needed to require the files like:

Dir.glob(File.join(File.dirname(__FILE__), 'base_classes/config/constants', "*.rb")) { |file| require file}
Dir.glob(File.join(File.dirname(__FILE__), 'base_classes', "*.rb")){ |file| require file}
Sweetening answered 19/7, 2011 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.