Recursively requiring a directory in Ruby

Ruby can recursively iterate through all files in a tree and this technique is frequently used to require all the files in a directory. Let’s use the following directory as an example:

a_directory/
  file_a.rb
  file_b.rb
  sub_directory/
    file_c.rb
    file_d.rb  

To create an array of all the files in ~/Desktop/a_directory/ use the following code:

Dir[Dir.pwd + "/**/*.rb"]

Provide Dir[] a path to the directory with all the contents you want to require and add “/**/*.rb” to the path to indicate you would like Ruby to recursively iterate through all subfolders and require all .rb files. Once an array of files is produced, it is easy to iterate over the array and require all the files.

Dir[Dir.pwd + "/**/*.rb"].each { |f| require f }

Files sometimes need to be loaded in a particular order. Let’s suppose we have a project/ folder with the following Ruby files.

project/
  cat.rb
  dog.rb
  mammal.rb

The code in these files is as follows:

# cat.rb
class Cat < Mammal
end

# dog.rb
class Dog < Mammal
end

# mammal.rb
class Mammal
end

Simply requiring all the files in the project directory will cause an error because the cat.rb and dog.rb files cannot be loaded until the mammal.rb is loaded. The mammal.rb file must be required first.

require Dir.pwd + "/mammal.rb"
Dir[Dir.pwd + "*.rb"].each { |f| require f }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s