在ruby中从一个目录中获取所有文件的最好方法是什么?
当前回答
Dir.glob(File.join('path', '**', '*.rb'), &method(:require))
或者,如果你想要将文件加载到特定的文件夹:
Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))
解释:
Dir。Glob以block作为参数。
方法(:require)将返回require方法。
&method(:require)将方法转换为块。
其他回答
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file|
require File.basename(file, File.extname(file))
end
如果您不剥离扩展名,那么您可能会需要相同的文件两次(ruby不会意识到“foo”和“foo. exe”。Rb”是相同的文件)。两次要求相同的文件可能会导致错误的警告(例如。"警告:已初始化的常量")。
试试require_all gem:
http://github.com/jarmo/require_all https://rubygems.org/gems/require_all
它让你简单地:
require_all 'path/to/directory'
在Rails中,你可以做:
Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
更新:修正了@Jiggneshh Gohel删除斜杠的建议。
如何:
Dir["/path/to/directory/*.rb"].each {|file| require file }
如果它是一个相对于执行要求的文件的目录(例如,你想加载lib目录中的所有文件):
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
编辑:根据下面的评论,更新版本:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }