Module | RequireAll |
In: |
lib/require_all.rb
|
Performs Kernel#autoload on all of the files rather than requiring immediately.
Note that all Ruby files inside of the specified directories should have same module name as the directory itself and file names should reflect the class/module names. For example if there is a my_file.rb in directories dir1/dir2/ then there should be a declaration like this in my_file.rb:
module Dir1 module Dir2 class MyFile ... end end end
If the filename and namespaces won‘t match then my_file.rb will be loaded into wrong module! Better to fix these files.
Set $DEBUG=true to see how files will be autoloaded if experiencing any problems.
If trying to perform autoload on some individual file or some inner module, then you‘d have to always specify *:base_dir* option to specify where top-level namespace resides. Otherwise it‘s impossible to know the namespace of the loaded files.
For example loading only my_file.rb from dir1/dir2 with autoload_all:
autoload_all File.dirname(__FILE__) + '/dir1/dir2/my_file', :base_dir => File.dirname(__FILE__) + '/dir1'
WARNING: All modules will be created even if files themselves aren‘t loaded yet, meaning that all the code which depends of the modules being loaded or not will not work, like usages of define? and it‘s friends.
Also, normal caveats of using Kernel#autoload apply - you have to remember that before applying any monkey-patches to code using autoload, you‘ll have to reference the full constant to load the code before applying your patch!
A wonderfully simple way to load your code.
The easiest way to use require_all is to just point it at a directory containing a bunch of .rb files. These files can be nested under subdirectories as well:
require_all 'lib'
This will find all the .rb files under the lib directory and load them. The proper order to load them in will be determined automatically.
If the dependencies between the matched files are unresolvable, it will throw the first unresolvable NameError.
You can also give it a glob, which will enumerate all the matching files:
require_all 'lib/**/*.rb'
It will also accept an array of files:
require_all Dir.glob("blah/**/*.rb").reject { |f| stupid_file(f) }
Or if you want, just list the files directly as arguments:
require_all 'lib/a.rb', 'lib/b.rb', 'lib/c.rb', 'lib/d.rb'
Works like require_all, but paths are relative to the caller rather than the current working directory