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
  • 78,473
  • 57
  • 200
  • 338
Ethan Turkeltaub
  • 2,931
  • 8
  • 30
  • 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

21

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
  • 25,705
  • 7
  • 65
  • 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
  • 296,393
  • 112
  • 651
  • 745
4

Try this:

Dir.glob(File.join(".", "**", "*.rb")).each do |file|
   require file
end
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • 1
    This will break on Ruby 1.9.2+, since '.' is no longer part of the search path for requires. An explicit leading '.' or `require_relative` is required. – Phrogz Dec 24 '10 at 21:24
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,808
  • 1
  • 20
  • 24