views:

4565

answers:

5

What's the best way to require all files from a directory in ruby ?

+30  A: 

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file }
Sam Stokes
You'll need to drop the .rb before requiring. Good other than that
rampion
According to the Pickaxe, the .rb extension is optional. Technically it changes the meaning: "require 'foo.rb'" requires foo.rb, whereas "require 'foo'" might require foo.rb, foo.so or foo.dll.
Sam Stokes
There's a subtle gotcha to not stripping the extension. If some other part of the code calls require 'foo' then ruby will load the same file again, which can lead to spurious errors. I added my own answer which explains that and shows how to strip the extension.
Pete Hodgson
+17  A: 

If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):

Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
jandot
thanks for this extra trick
Gaetan Dubar
+5  A: 

The best way is to add the directory to the load path and then require the basename of each file. This is because you want to avoid accidentally requiring the same file twice -- often not the intended behavior. Whether a file will be loaded or not is dependent on whether require has seen the path passed to it before. For example, this simple irb session shows that you can mistakenly require and load the same file twice.

$ irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> require './test'
=> true
irb(main):003:0> require './test.rb'
=> false
irb(main):004:0> require 'test'
=> false

Note that the first two lines return true meaning the same file was loaded both times. When paths are used, even if the paths point to the same location, require doesn't know that the file was already required.

Here instead, we add a directory to the load path and then require the basename of each *.rb file within.

dir = "/path/to/directory"
$LOAD_PATH.unshift(dir)
Dir[File.join(dir, "*.rb")].each {|file| require File.basename(file) }

If you don't care about the file being required more than once, or your intention is just to load the contents of the file, perhaps load should be used instead of require. Use load in this case, because it better expresses what you're trying to accomplish. For example:

Dir["/path/to/directory/*.rb"].each {|file| load file }
Ryan McGeary
+2  A: 

Try the require_all gem:

http://github.com/tarcieri/require_all/tree/master

It lets you simply:

require_all 'path/to/directory'

+6  A: 
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file| 
  require File.basename(file, File.extname(file))
end

If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").

Pete Hodgson