These days I started to play with Ruby and I needed to figure out how to load my own scripts from a sub-directory into my project folder.
I needed to do it because Ruby 1.9.3 does not include the current directory in its default loader path and if one issues a require or load command to a file that is not in the current Ruby loader path he/she will get the an error message like no such file to load.
My project structure is as follow:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
my-project/ +-configuration/ | +-config.yml | +-images/ | +-img1.png | +-img2.png | +-lib/ | +-script1.rb | +-script2.rb | +-script3.rb | +-main.rb |
Picture 1 – Project structure
After some research in the net I found out a couple of methods. The one I liked more is the following:
|
1 |
$LOAD_PATH << './lib' |
Listing 1 – adding your own folders to Ruby loader PATH
You just have to add it into your main script (the one that will load the others) prior to require command. So, my main ruby file became something like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/usr/bin/env ruby $LOAD_PATH << './lib' require 'script1' require 'script2' require 'script3' s1 = Script1.new # defined in lib/script1.rb s2 = Script1.new # defined in lib/script2.rb s3 = Script1.new # defined in lib/script3.rb s1.method1 s2.method2 s3.method3 |
Listing 2 – main.rb excerpt.
Enjoy.
Please, try my games, play free on-line games on my site, tweet this post url and share it on facebook, google+ and other social medias.


Pingback: How to create your own plugins for your Ruby programs | Plicatibu Software Development