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:
- Use
require_relative "../lib/app"
- Add
lib
to$LOAD_PATH
inbin/console
:$LOAD_PATH.unshift "./lib"
- 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
What Are the Brackets [5.1] After Activerecord Migration and How Does It Work
Nokogiri/Xpath Namespace Query
Altering the Primary Key in Rails to Be a String
What's the Best Way to Use Soap With Ruby
Converting Camel Case to Underscore Case in Ruby
Saving Enum from Select in Rails 4.1
How to Extract Url Parameters from a Url With Ruby or Rails
Using Helpers in Model: How to Include Helper Dependencies
What's Different Between Each and Collect Method in Ruby
Paginating an Array in Ruby With Will_Paginate
When to Use 'Self.Foo' Instead of 'Foo' in Ruby Methods