Load Path
This gem is written to make it easy to configure the load path in Ruby files. Simple use a configure block to setup your load path without ugly code to interact with the file system.
===================
Contributing
For questions and to report bugs, nayyara.samuel@opower.com. For contributing to code, send a pull request with a detailed description of changes to this repo.
Installing
To build the gem use the rake commands for gem tasks. To install:
rake install
Usage
If you have been programming Ruby you will notice that require_relative
is not encouraged. The alternative is to setup your load path with code that looks something like the following:
“his_dir = File.dirname(__FILE__)
Add the folder lib 2 levels above
lib_dir = File.join(this_dir, ‘..’, ‘..’, ‘lib’) $: « lib_dir
Add the folder utils to load path
utils_dir = File.join(this_dir, ‘..’, ‘utils’) $: « utils_dir
Add the folder others under this directory to load path
others_dir = File.join(this_dir, ‘others’) $: « others_dir
“
And so forth. You can make the code look nicer but the line $: << some_directory
looks ugly. With LoadPath your code looks something like this:
“equire ‘load_path`
LoadPath.configure do add parent_directory(‘lib’, up: 2) add sibling_directory(‘utils’) add child_directory(‘others’) end “
You can then proceed to require the files with require
instead of require_relative
as normal. NOTE: You must first have the desired directory on the load path before requiring files from it.
The configure block also lets you require your files in bulk. For example to require all files in the lib folder 2 levels above, you would write code like this:
“Dir.glob(File.join(this_dir, ‘..’, ‘..’, ‘lib’, ‘.rb’)) do |file| require File.basename(file) end
“
Which can be made cleaner with:
“oadPath.configure do add parent_directory(‘lib’, up: 2) add sibling_directory(‘utils’)
require_all parent_directory(‘lib’, up: 2), ‘.rb’ # Default is ‘.rb’, so missing second option works for Ruby source files require_all sibling_directory(‘utils’) end
“
Examples
See also the example under Rspec tests with directory structure: