Is it possible to recursively require all files in

2020-02-25 04:01发布

I am working on an API that needs to load all of the .rb files in its current directory and all subdirectories. Currently, I am entering a new require statement for each file that I add but I would like to make it where I only have to place the file in one of the subdirectories and have it automatically added.

Is there a standard command to do this?

6条回答
Rolldiameter
2楼-- · 2020-02-25 04:20

like Miguel Fonseca said, but in ruby >= 2 you can do :

    Dir[File.expand_path "lib/**/*.rb"].each{|f| require_relative(f)}
查看更多
Evening l夕情丶
3楼-- · 2020-02-25 04:29

I use the gem require_all all the time, and it gets the job done with the following pattern in your requires:

require 'require_all'
require_all './lib/exceptions/'
查看更多
Fickle 薄情
4楼-- · 2020-02-25 04:35
def rLoad(dir)
    Dir.entries(dir).each {|f|
        next if f=='.' or f=='..'
        if File.directory?(f)
            rInclude(f)
        else
            load(f) if File.fnmatch('*.rb', f)
        end
    }
end

This should recursively load all .rb files in the directory specified by dir. For example, rLoad Dir.pwd would work on the current working directory.

Be careful doing this, though. This does a depth-first search and if there are any conflicting definitions in your Ruby scripts, they may be resolved in some non-obvious manner (alphabetical by folder/file name I believe).

查看更多
做自己的国王
5楼-- · 2020-02-25 04:40

In this case its loading all the files under the lib directory:

Dir["#{File.dirname(__FILE__)}/lib/**/*.rb"].each { |f| load(f) }
查看更多
贪生不怕死
6楼-- · 2020-02-25 04:43
require "find"

Find.find(folder) do |file|
  next if File.extname(file) != ".rb"
  puts "loading #{file}"
  load(file)
end

This will recursively load each .rb file.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-02-25 04:43

You should have a look at this gem. It is quite small so you can actually re-use the code instead of installing the whole gem.

查看更多
登录 后发表回答