Use Ruby Class In A Different Directory
Question
I have written a few ruby classes. However, when trying to access one from another directory I am getting the following error:
uninitialized constant Main::AppVersion
This is what the directory structure looks like:
home --> a --> app_version.rb
home --> b --> c --> lib --> main.rb (and other classes)
Everything within "lib" can see each other. However, when trying to access app_version, it fails. I added the path to app version (home/a) to the $LOAD_PATH. So it should be available from there. I have also tried "requiring" my other class, but when I do that I get the following error:
LoadError: no such file to load -- AppVersion
Any idea on what I could be doing wrong here would be highly appreciated. Thanks!
Solution
Can try using require_relative:
require_relative '../../../a/app_version'
OTHER TIPS
You error is:
LoadError: no such file to load -- AppVersion
So require
is looking for a file AppVersion.rb
. And you said the file name is app_version.rb
. Try to load it with:
require 'app_version'
after setting up the $LOAD_PATH
.
When you define Main::AppVersion class it's supposed to reside in main folder (i.e. main/app_version.rb)
So it doesn't depend on $LOAD_PATH.
You will have to require the file.
LoadError: no such file to load -- AppVersion
Do you require "app_version"
? Or require "AppVersion"? (first one is correct, and consider to require_relative
)
Another option is to run ruby and give the include path like
ruby -Ia -Ib/c/lib b/c/lib/main.rb
.