0

I have a file required.rb required by other files main.rb and tester.rb, each of which is invoked separately and run separately.

Within required.rb, I want to require all files in a subdirectory of the required file. The whole thing looks something like this:

main.rb
lib/
   required.rb
   req_files/
      req1.rb
      req2.rb
      req3.rb
tester/
   tester.rb

The code to import the required files looks like:

Dir[Dir.pwd + "/req_files/*.rb"].each do  |file|
  require file
end

In suggested strategies I have seen, be it utilizing Dir.pwd or __FILE__, the context applied to required.rb's location is the context of whichever original file required it in the first place, which means that I can't support requiring from both of those files separately with the current setup.

Is there a way to denote a path relative to the actual required.rb?

EDIT :

It's not though, because changing require to require_relative doesn't change the fact that Dir[Dir.pwd + "/req_files/*.rb"] and more specifically Dir.pwd resolves with respect to the original file (main or tester), so it cannot be expressed as is in required and work for both entry points

Also note that required.rb is required via require_relative already from both main.rb and tester.rb.

Bennett Talpers
  • 802
  • 6
  • 9
  • Possible duplicate of [What is the difference between require\_relative and require in Ruby?](https://stackoverflow.com/questions/3672586/what-is-the-difference-between-require-relative-and-require-in-ruby) – Brad Werth Oct 24 '17 at 17:18
  • @BradWerth: not really a _duplicate_, though. Because this question doesn't mention `require_relative`. – Sergio Tulentsev Oct 24 '17 at 17:19
  • 1
    There were better "duplicates" that made worse targets. I was looking at it sorta like how https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it gets used... – Brad Werth Oct 24 '17 at 17:20
  • 1
    I think the duplicate is justified, as it is clearly the information the OP is seeking. If not this one, I bet I could find at least one more require_relative question in the last 10 years of ruby questions.... – Brad Werth Oct 24 '17 at 17:22

2 Answers2

0

Is there a way to denote a path relative to the actual required.rb

Yes, kinda. There's another method for this.

http://ruby-doc.org/core-2.4.2/Kernel.html#method-i-require_relative

require_relative(string) → true or false

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

I was incorrect regarding __FILE__; Using File.dirname(__FILE__) instead of Dir.pwd works for giving the directory of the actual file versus the directory of the invoking file.

Bennett Talpers
  • 802
  • 6
  • 9