Adding a Directory to $Load_Path (Ruby)

Adding a directory to $LOAD_PATH (Ruby)

I would say go with $:.unshift File.dirname(__FILE__) over the other one, simply because I've seen much more usage of it in code than the $LOAD_PATH one, and it's shorter too!

Ruby - adding a directory to $LOAD_PATH - what does it do?

When you add the /Users/you/scripts/ruby directory to the load path, you can use:

require 'example'

instead of:

require '/Users/you/scripts/ruby/example.rb'

How to add 'lib' to LOAD_PATH using Gemfile without gemspec?

There's a few ways:

  1. Use require_relative "../lib/app"
  2. Add lib to $LOAD_PATH in bin/console: $LOAD_PATH.unshift "./lib"
  3. Just add it inline on the command line: bundle exec ruby -Ilib bin/console

Note though that if you're using require_relative in your app (and you should be), then lib doesn't need to be in $LOAD_PATH, you should just be able to require "path/to/app" wherever you want to load it.

Add $LOAD_PATH externally

RUBYLIB environment variable is a colon separated list of paths which ruby will prepend the the standard LOAD_PATH. ruby -I path on the command line is also the same as $LOAD_PATH.unshift 'path' in your code. Ruby will also process options from environment var RUBYOPT.

how can I add current directory to ruby loadpath permanently

Set the RUBYLIB environment variable for your shell to include the current path .. If you want multiple paths to search from, you can separate each path with :.

export RUBYLIB=.

Test:

$ RUBYLIB='.' ruby -e "p $:"

UPDATE: Put the environment variable settings in your shell's initialization script so that it gets set every time you launch your shell.

Understanding Ruby's load paths

Ruby's $LOAD_PATH will not include your lib directory by default (even though that's where the file you're running is located).

You can either tell the ruby interpreter to include it:

ruby -Ilib lib/processor.rb

Or you can add the lib folder to the load path:

$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'processor/mapper'
...


Related Topics



Leave a reply



Submit