13

I have the following directory tree.

- app.rb
- folder/
  - one/
    - one.rb
  - two/
    - two.rb

I want to be able to load Ruby files in the folder/ directory, even the ones in the sub-directories. How would I do so?

Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
Ethan Turkeltaub
  • 2,871
  • 6
  • 29
  • 45
  • 1
    Duplicate of http://stackoverflow.com/questions/735073/best-way-to-require-all-files-from-a-directory-in-ruby . Use the *require_all* gem and do `require 'require_all'; require_rel 'one'` in `one.rb`. – clacke Jun 09 '11 at 08:39

4 Answers4

20

Jekyll does something similar with its plugins. Something like this should do the trick:

    Dir[File.join(".", "**/*.rb")].each do |f|
      require f
    end
Brian Clapper
  • 24,425
  • 7
  • 63
  • 65
  • 2
    In case you have inheritance, you'll want to sort the files that are required so that the top level classes are required first. Dir[File.join("#{Rails.root}/app/classes", "**/*.rb")].sort_by {|path| path.split("/").length }.each do |f| require f end – Ryan Francis May 24 '15 at 17:35
18

With less code, but still working on Linux, OS X and Windows:

Dir['./**/*.rb'].each{ |f| require f }

The '.' is needed for Ruby 1.9.2 where the current directory is no longer part of the path.

Phrogz
  • 284,740
  • 104
  • 634
  • 722
4

Try this:

Dir.glob(File.join(".", "**", "*.rb")).each do |file|
   require file
end
Jacob Relkin
  • 156,685
  • 31
  • 339
  • 316
2

In my project this evaluates to ["./fixset.rb", "./spec/fixset_spec.rb", "./spec/spec_helper.rb"] which causes my specs to run twice. Therefore, here's a tweaked version:

Dir[File.join(".", "**/*.rb")].each { |f| require f unless f[/^\.\/spec\//]}

This'll safely ignore all *.rb files in ./spec/

Michael De Silva
  • 3,788
  • 1
  • 19
  • 24