ChatGPT解决这个技术问题 Extra ChatGPT

Best way to require all files from a directory in ruby?

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


J
JasonSmith

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file }

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.
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, is this still true? See Rene's comment below.
This might be obvious, but its worth noting that dropping the .rb will also require any non-.rb files in the dir, which might not be desired.
@PeteHodgson's suggestion is inaccurate. Ruby's 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).
F
FeifanZ

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 }

You can also add all child directories like this Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each {|file| require file }
It's probably safer to use File.join rather than making assumptions about forward/backward slashes: Dir[File.join(File.dirname(__FILE__), 'lib', '*.rb')].each {|file| require file }
There is also require_relative
If you're using >= ruby 2.0, you can use __dir__ instead of File.dirname(__FILE__).
@maasha How do you use 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'

I needed to include all of my ActiveRecord models, the require_all gem figured out all of the dependencies and required them perfectly. Thanks!
@panupan Just be aware that 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.
It doesn't have sense to bloat your app with gems that you can simply replace with a line of code. This increases the load time of your app and induces more bugs at long term.
P
Pete Hodgson
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").


Is this really the case? Documentation says: A feature will not be loaded if its name already appears in $". The file name is converted to an absolute path, so "require 'a'; require './a'" will not load a.rb twice. ruby-doc.org/core/classes/Kernel.html#M001418
My testing shows the same that Derek said: require "foo.rb"; require "foo"; will load foo.rb just once.
@PeteHodgson- Can you back this up?
No. Ruby's 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).
m
metakungfu
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.


This is some beautiful code. I love how there are no visible blocks.
Dir.glob( File.join( File.dirname(__FILE__), '{lib,addons}', 'subfolder', '**', '*.rb' ), &method(:require) ) eliminates dependence on platform (such as '/' or '\'). Works well. Thanks.
R
Ryan McGeary

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 }

This seems to be the best solution to require all files while avoiding any accidental double requiring of files - and should be marked as the accepted answer ...
I feel like something has changed since 2009. require now needs ./ and require_relative realises those are paths to the same file.
s
shushugah
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.


K
Koen.

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__.


this seems definitely the way to go, and most up to date answer, after trying all the rest, +1 for File.expand_path
I definitely prefer this answer to the accepted one. Various Rails.root.join answers also work if you're in rails.
D
Dan Kohn

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.


Since 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)
Thanks for the recommendation; I edited to include your comment.
Using a forward slash (/) for sub-directories under Rails.root, for e.g. 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 }
@Jiggneshh Gohel I removed slashes as you suggested, thanks.
J
Jazz

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 }


A
Aleksander

And what about: require_relative *Dir['relative path']?


Require relative doesn't take multiple files: ruby-doc.org/core-2.1.2/Kernel.html#method-i-require_relative
OK, but in my example it isn't. The '*' changes arity to 1. It works as multiple call to require_relative.
The '*' changes arity to 1 - What do you mean with it? 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)