Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby uninitialized constant error when loading all files in a directory

Tags:

ruby

I am trying to load all of the ruby files in a directory from a Ruby file using this code:

Dir["#{File.dirname(__FILE__)}/pages/*_page.rb"].each { |r| load r }

However, in this directory I have a Class Bar which inherits from Class Foo.

Class Bar < Foo

When I run my program, I get an error: uninitialized constant Foo (NameError).

I think this is because it is trying to load the Bar class, but has not yet loaded the Foo class.

I have tried explicitly requiring Foo inside of Bar, but then I will get warnings as Foo will have been loaded twice.

How can I load all the files in a directory, in such a way that it will require any needed files automatically.

like image 937
m4cola Avatar asked Jan 23 '26 10:01

m4cola


1 Answers

Since there is no real way to force the order that files are required when using a loop, you would first have to require the file that defines Foo before your loop.

require "./pages/file_that_defines_foo.rb"
Dir["#{File.dirname(__FILE__)}/pages/*_page.rb"].each { |r| load r }
like image 67
Eugene Avatar answered Jan 25 '26 02:01

Eugene