Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 280 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to recursively require all files in a directory in Ruby?

#1
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?
Reply

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

require 'require_all'
require_all './lib/exceptions/'

[1]:

[To see links please register here]

Reply

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

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

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


[1]:

[To see links please register here]

Reply

#5
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).
Reply

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

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

#7
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through