Is it possible to recursively require all files in a directory in Ruby?
In this case its loading all the files under the lib directory:
Dir["#{File.dirname(__FILE__)}/lib/**/*.rb"].each { |f| load(f) }
Best way to require all files from a directory in ruby?
How about:
Dir["/path/to/directory/*.rb"].each {|file| require file }
Require all files in sub-directory
Jekyll does something similar with its plugins. Something like this should do the trick:
Dir[File.join(".", "**/*.rb")].each do |f|
require f
end
One-liner to recursively list directories in Ruby?
Dir.glob("**/*/") # for directories
Dir.glob("**/*") # for all files
Instead of Dir.glob(foo)
you can also write Dir[foo]
(however Dir.glob
can also take a block, in which case it will yield each path instead of creating an array).
Ruby Glob Docs
What's a good way to require a whole directory tree in Rails?
autoload_paths
and friends work only if the given files, or files in the given directories, are named according to the rails naming conventiion.
e.g. if a file some_class.rb
is given to autoload_paths
, it expcects the file to declare a class SomeClass
, and sets up some magic to make any reference to SomeClass
load that file on-the-fly.
So if you want to have it only load each of your files as they are needed, then you will have to name your files accordingly, and have one file per class.
If you are happy to load all of the files in a directory tree when rails starts, you can do this:
Dir.glob("/path/to/my/lib/**/*.rb").each { |f| require f }
The above will read every .rb
file in /path/to/my/lib
, and any directories under it.
Running files in a directory recursively using ruby
Depends what you mean by "run". To just execute the code that is in each script within the same ruby process, this will do the trick:
Dir["scripts/**/*.rb"].each{|s| load s }
But it you want to run each script in it's own ruby process, then try this:
Dir["scripts/**/*.rb"].each{|s| puts `ruby #{s}` }
Just put the either of these in the contents of run-all.rb
and the run ruby run-all.rb
form the command line.
How to require all files in a directory, in a gem?
Rubygems has a facility called find_files that will allow you to search based anything in the load path:
Gem.find_files("my_gem/files/**/*.rb").each { |path| require path }
Related Topics
Rails - Displaying Foreign Key References in a Form
Model Using Modules in Rails Application
Cucumber + Webrat + Selenium Guide
Sinatra Static Assets Are Not Found When Using Rackup
How to Ignore Multiline Comments in SASS
Get Link and Href Text from HTML Doc with Nokogiri & Ruby
How to Use Basic Authentication with Httparty in a Rails App
Ruby: How to Group a Ruby Array
Rspec Stubbing Method for Only Specific Arguments
How to Get an Empty Temporary Directory in Ruby on Rails
Differencebetween "Rails S" and "Bundle Exec Rails S"
Routing Error - Uninitialized Constant
Retrieve Contents of Url as String
Ruby: No Such File or Directory @ Rb_Sysopen - Testfile (Errno::Enoent)