Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Ruby's load paths

Tags:

ruby

I'm a little confused about why my project can't load the files it needs, it's a really simple project tree:

processor/   bin/   lib/     processor.rb     processor/       mapper.rb       reducer.rb 

and my processor.rb file looks like

require 'processor/mapper' require 'processor/reducer'  class Processor  end 

And just for testing it that file mapper looks like:

class Mapper   def run     puts "running map"   end end 

But running ruby lib/processor.rb results in:

<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- processor/mapper (LoadError)     from <internal:lib/rubygems/custom_require>:29:in `require'     from lib/processor.rb:3:in `<class:Processor>'     from lib/processor.rb:2:in `<main>'     
like image 407
JP Silvashy Avatar asked Jul 12 '11 21:07

JP Silvashy


People also ask

What is load path in ruby?

Ruby by default has a list of directories it can look through when you ask it to load a specific file. This is stored in a variable: $: This is the load path. It initially includes the libdir, archdir, sitedir, vendordir and some others and is information Ruby holds about itself. If you type ruby -e 'puts $LOAD_PATH'

What is Load_path?

$LOAD_PATH is an array of absolute paths i.e it stores the exact location of all the dependencies in the project. The require keyword searches for the dependencies in the array $LOAD_PATH and tries to load it for the file that has a dependency on certain library.

What is the difference between load and require?

You should use load function mainly for the purpose of loading code from other files that are being dynamically changed so as to get updated code every time. Require reads the file from the file system, parses it, saves to the memory, and runs it in a given place.


1 Answers

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' ... 
like image 88
Dylan Markow Avatar answered Sep 18 '22 17:09

Dylan Markow