Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to require all files from a directory in ruby?

What's the best way to require all files from a directory in ruby ?

like image 218
Gaetan Dubar Avatar asked Apr 09 '09 17:04

Gaetan Dubar


People also ask

How do I use require 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.

What is require relative in Ruby?

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.

How do I put the file path in Ruby?

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.

How do I change directory in Ruby?

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.


2 Answers

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file } 
like image 93
Sam Stokes Avatar answered Sep 22 '22 22:09

Sam Stokes


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 } 
like image 39
jandot Avatar answered Sep 21 '22 22:09

jandot