How to fix CLI load error : `require_relative': cannot load such file -Ruby

I've tried the solutions provided on Stackoverflow, related to this error. I have also tried a trial and error approach by rebuilding my gem and the error is still raised.

Error below:

./bin/coding-schools:3:in require_relative': cannot load such file -- /home/Jenhop8786/ temporary/coding_schools/bin/lib/coding_schools (LoadError) from ./bin/coding-schools:3:in'

In my bin folder my file looks like this:

#!/usr/bin/env ruby

require_relative './lib/coding_schools'

CodingSchools::CLI.new.call

In my lib folder my file looks like this:

require_relative "./coding_schools/version"
require_relative "./coding_schools/cli"

Project Directory:

-->Temporary
-->coding_schools 
 ->bin
   -coding-schools
   -console 
   -setup 
 ->lib
   -cli.rb
   -coding_schools.rb
   -version.rb
-gitignore
-coding_schools.gemspec
-Gemfile
-LICENSE
-Rakefile
-README.md

1 answer

  • answered 2018-01-13 17:43 David Grayson

    Try removing ./ from the require_relative. The . refers to your current working directory where you started the Ruby process.

    You can use ../ to go up one directory if needed.

    With your particular directory structure, files in bin (or lib) can load files in lib using code like this:

    require_relative '../lib/cli'
    require_relative '../lib/coding_schools'
    require_relative '../lib/version'
    

    Files in lib can load eachother with code like this:

    require_relative 'cli'
    require_relative 'coding_schools'
    require_relative 'version'
    

    If you are really making a gem though, I'd recommend putting every file in lib into a subdirectory with the same name as your gem. That is the convention. But after you do that, you have to fix some relative includes, so you should first get your code working and mark this as the accepted answer, then look into that.