Understanding Ruby's load paths

Ruby

Ruby Problem Overview


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>'    

Ruby Solutions


Solution 1 - Ruby

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'
...

Solution 2 - Ruby

Ruby 1.9 no longer includes "." in the load path. Do require "#{File.dirname(__FILE__)}/processor/mapper" or use require_relative.

You can always determine the current load path by inspecting $LOAD_PATH (or $:)

(edited: $LOAD_PATH not $:LOAD_PATH)

Solution 3 - Ruby

Use Ruby's require_relative in this case:

require_relative "processor/mapper"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJP SilvashyView Question on Stackoverflow
Solution 1 - RubyDylan MarkowView Answer on Stackoverflow
Solution 2 - RubycamView Answer on Stackoverflow
Solution 3 - RubyAldo 'xoen' GiambellucaView Answer on Stackoverflow