0

I am trying to require all the projects from the projects and sub_projects folders.

Dir Structure:

|-- project_manager
    -- run_farm.rb
    -- projects
       -- build_coop.rb
       -- sub_projects
          -- count_apples.rb
          -- count_chickens.rb

I found this answer but was unable to get it to work: Best way to require all files from a directory in ruby?

Original syntax from the link: Dir["/path/to/directory/*.rb"].each {|file| require file }

So, in run_farm.rb, I tried this:

path_to_directory = File.dirname(File.absolute_path(__FILE__))
Dir[path_to_directory + '/projects/**/*'].each { |file| require file }

Also tried:

path_to_directory = File.dirname(File.absolute_path(__FILE__))
Dir[path_to_directory + '/projects/**/*'].each { |file| require "#{file}" }

When I run run_farm.rb, I get this error: .rbenv/versions/2.6.6/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in require'

I was able to run this, so I know something works:

path_to_directory = File.dirname(File.absolute_path(__FILE__))
Dir[path_to_directory + '/projects/**/*'].each { |file| puts "#{file}" }

Found this but it didn't help me: https://github.com/rbenv/rbenv/issues/1158

I hope I provided enough info. Does anyone know what I am doing wrong?

  • It works for me when I change `'/projects/**/*'` to `'/projects/**/*.rb'`. I put the line `puts "in file blah"` in each of the required files, substituting the actual file name for "blah" to confirm that they were all being loaded. – pjs Aug 27 '21 at 04:19

1 Answers1

0

To require all the files, there is a special gem which does an amazing job. It's require_all but don't install the lastest one.

Install

gem install require_all -v 1.5.0

It provides two beautiful methods require_all() and require_rel()! For require_rel, paths are relative to the caller rather than the current working directory

Rajagopalan
  • 5,465
  • 2
  • 11
  • 29