What's the best way to require all files from a directory in ruby ?
The require method takes the name of the file to require, as a string, as a single argument. This can either be a path to the file, such as ./lib/some_library. rb or a shortened name, such as some_library. If the argument is a path and complete filename, the require method will look there for the file.
require_relative allows you to "load a file that is relative to the file containing the require_relative statement". With require , ./ indicates a path that is relative to your current working directory. – Ajedi32.
Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.
chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.
How about:
Dir["/path/to/directory/*.rb"].each {|file| require file }
If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
Edit: Based on comments below, an updated version:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With