要求ruby目录中的全部文件的最佳方法?

要求ruby目录中的全部文件的最佳方法是什么? ruby


#1楼

Dir.glob(File.join('path', '**', '*.rb'), &method(:require))

或者,若是要将文件范围加载到特定文件夹: app

Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))

说明: ui

Dir.glob以块为参数。 spa

method(:require) 将返回require方法。 code

&method(:require)会将方法转换为bloc。 get


#2楼

我没有像在某些答案中那样链接路径,而是使用File.expand_pathio

Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
  require file
end

更新: import

您能够执行如下操做,而不是使用File.dirnamerequire

Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
  require file
end

Where .. __FILE__的文件名。 扩展


#3楼

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

若是你没有剥离扩展,那么你最终可能须要两次相同的文件(ruby不会意识到“foo”和“foo.rb”是同一个文件)。 两次须要相同的文件会致使虚假警告(例如“警告:已经初始化常量”)。


#4楼

我参加派对已经晚了几年,可是我有点喜欢这个单行解决方案,我曾经习惯性地将全部内容都包含在app / workers / Concer中:

Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }


#5楼

在Rails中,您能够:

Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }

更新:修正了@Jiggneshh Gohel删除斜线的建议。

相关文章
相关标签/搜索