How about:
Dir["/path/to/directory/*.rb"].each {|file| require file }
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 }
Edit: Based on comments below, an updated version:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each {|file| require file }
Dir[File.join(File.dirname(__FILE__), 'lib', '*.rb')].each {|file| require file }
__dir__
instead of File.dirname(__FILE__)
.
require_relative
to require all files in a directory?
Try the require_all gem:
http://github.com/jarmo/require_all https://rubygems.org/gems/require_all
It lets you simply:
require_all 'path/to/directory'
require_all
's cyclic dependency resolution works around a problem in your source code: you have Ruby source files that do not require their dependencies. This shuts the door on scalpel loading, committing you to all-or-nothing loading. That's not a problem in small libraries, but it's a decision you should be making consciously.
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").
require "foo.rb"; require "foo";
will load foo.rb
just once.
require
is not confused by the presence or absence of the .rb
extension. Tested on MRI 1.8.7-p374, 2.1.5 and 2.2.0. This urban legend comes from Rails, where "clever" autoloading exhibited the behaviour described in older versions (and may still exhibit it).
Dir.glob(File.join('path', '**', '*.rb'), &method(:require))
or alternatively, if you want to scope the files to load to specific folders:
Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))
explanation:
Dir.glob takes a block as argument.
method(:require) will return the require method.
&method(:require) will convert the method to a bloc.
Dir.glob( File.join( File.dirname(__FILE__), '{lib,addons}', 'subfolder', '**', '*.rb' ), &method(:require) )
eliminates dependence on platform (such as '/' or '\'). Works well. Thanks.
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 }
require
now needs ./
and require_relative
realises those are paths to the same file.
Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
require file
end
This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.
Instead of concatenating paths like in some answers, I use File.expand_path
:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname
you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where ..
strips the filename of __FILE__
.
File.expand_path
Rails.root.join
answers also work if you're in rails.
In Rails, you can do:
Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
Update: Corrected with suggestion of @Jiggneshh Gohel to remove slashes.
Rails.root
is a Pathname
instance, you can do this in any Ruby environment, not just Rails (N.B. Rails.root.join('lib/ext/*.rb')
reads a little nicer)
Rails.root.join('/lib')
doesn't generate correct path. I found this one to work correctly: Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:
Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }
And what about: require_relative *Dir['relative path']
?
require_relative *Dir['*.rb']
work, if there is only one ruby-script. But if multiple ruby scripts are found, you get require_relative': wrong number of arguments (4 for 1) (ArgumentError)
Success story sharing
require
is not confused by the presence or absence of the.rb
extension. Tested on MRI 1.8.7-p374, 2.1.5 and 2.2.0 tested. This urban legend comes from Rails, where "clever" autoloading exhibited the behaviour he describes in older versions (and may still exhibit it).