-2

I got this 'require' cannot load such file error.

I got this previously and I added

__LIB_DIR__ = File.expand_path(File.join(File.dirname(__FILE__), ".."))
unless $LOAD_PATH.include?(__LIB_DIR__)
  $LOAD_PATH.unshift(__LIB_DIR__)
end

I would like to know what this does? I added this in a main 'require' file of my project. Now I write a test case,

$:.unshift File.join(File.dirname(__FILE__), ".")

I try to run it, I get the LoadError. I also tried require_relative no luck.

Structure:

Main
  Git
  lib
     files.rb
    base.rb
  test
     test1.rb

I have the first code block above in base.rb where I do all 'requires' and when i try to run the test. I get LoadError.

'Please',Explain the first and second code blocks also give me a solution

druuu
  • 1,676
  • 6
  • 19
  • 36
  • That's a super messy solution. What `require_relative` line did you use? That should work. Keep in mind `$:` and `$LOAD_PATH` are the same thing. – tadman Nov 24 '14 at 19:24
  • 1
    Can you add a "please" to this sentence: "Explain the first and second code blocks also give me a solution"? It sounds like a demand. – Jared Beck Nov 24 '14 at 19:27
  • It sounds like you want the moon. What exactly is the question, even? – matt Nov 24 '14 at 19:43

1 Answers1

0

For clarity, instead of

__LIB_DIR__ = File.expand_path(File.join(File.dirname(__FILE__), ".."))

use

__LIB_DIR__ = File.expand_path('..', File.dirname(__FILE__))

What does this do?

unless $LOAD_PATH.include?(__LIB_DIR__)
  $LOAD_PATH.unshift(__LIB_DIR__)
end

Consider this:

ary = %w[a b]
ary # => ["a", "b"]
ary.unshift('c')
ary # => ["c", "a", "b"]

I try to run it, I get the LoadError. I also tried require_relative no luck.

That could be for a number of reasons, but, unfortunately you didn't share the code where it occurs. require and require_relative are both used to load code, but have different syntax in the parameter passed. We'd need to know what you're trying to load, and where it is in the file hierarchy in relation to your calling script.

Perhaps one of these, or their related questions, would help:

Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303