开发者

Is it possible to recursively require all files in a directory in Ruby?

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 t开发者_JAVA百科o 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?


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

Dir["#{File.dirname(__FILE__)}/lib/**/*.rb"].each { |f| load(f) }


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.


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

    Dir[File.expand_path "lib/**/*.rb"].each{|f| require_relative(f)}


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/'


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜