What are best practices for using require in Ruby?

dependencies, require, ruby

Solution

Let's evaluate each option:

Put all the require lines in a file (like init.rb)

This means each individual file will be less cluttered, as `require`s will all be in one place. However, it can happen that the order in which they are written matters, so you end up effectively doing dependency resolution manually in this file.

require files at the top of each model file

Each file will have a little more content, but you won't have to worry about ordering as each file explicitly requires the dependencies it needs. Calling `require` for the same file multiple times has no effect.

This also means that you can require only parts of your code, which is useful for libraries; e.g. `require active_support/core_ext/date/calculations` gets only the part of the library the external app needs.

Of the two, I'd pick the second. It's cleaner, requires less thinking, and makes your code much more modular.

Problem

Some models require other models to be loaded first. But each required file only needs to be loaded once. What is the best way to manage this? Put all the require lines in a file (like init.rb), or require files at the top of each model file?

Original source