4

I have a directory structure that looks like this:

 - lib
   - yp-crawler (directory)
      - file-a.rb
      - file-b.rb
      - file-c.rb
   - yp-crawler.rb

My lib/yp-crawler.rb file looks like this:

require "yp-crawler/file-c"
require "yp-crawler/file-b"
require "yp-crawler/file-a"

module YPCrawler
end

When I try to run my file at the command line by doing this:

ruby lib/yp-crawler.rb

I get this error:

`require': cannot load such file -- yp-crawler/file-c (LoadError)
    from .rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from lib/yp-crawler.rb:1:in `<main>'

What could be causing this?

2
  • 1
    have you tried require_relative "file-a"? Commented Sep 28, 2016 at 12:26
  • 1
    @davidhu2000 Bruv...perfect. That worked. Add it as an answer, and I will accept that. Thanks! Commented Sep 28, 2016 at 12:30

2 Answers 2

5

According to API Dock, require_relative is what you need.

Ruby tries to load the library named string relative to the requiring file’s path. If the file’s path cannot be determined a LoadError is raised. If a file is loaded true is returned and false otherwise.

So all you have to do is

require_relative "file-a"
require_relative "file-b"
require_relative "file-c"
Sign up to request clarification or add additional context in comments.

1 Comment

Out of curiosity, was this a new change since 1.8/1.9?
3

Another thing you can do is to add the directory to $LOAD_PATH (this is how most of the gems require files).
$LOAD_PATH (aka $:) is where ruby looks for a file when you call require.

So you can try this code

# lib/yp-crawler.rb

$LOAD_PATH.unshift File.expand_path('..', __FILE__)
# it can be $LOAD_PATH.push also

require "yp-crawler/file-c"
require "yp-crawler/file-b"
require "yp-crawler/file-a"

module YPCrawler
end

P.S. For example you can see how paperclip does the same thing.

1 Comment

I was just going to post this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.