Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are best practices for using require in Ruby?

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?

like image 369
B Seven Avatar asked Oct 22 '12 00:10

B Seven


People also ask

When should load be used in Ruby as opposed to require?

You should use load function mainly for the purpose of loading code from other files that are being dynamically changed so as to get updated code every time. Require reads the file from the file system, parses it, saves to the memory, and runs it in a given place.

Where does Ruby look for require?

Ruby looks in all the paths specified in the $LOAD_PATH array.

How do you require a class in Ruby?

To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top. For instance, if I defined class Foo in foo. rb , in bar. rb I would have the line require 'foo' .


2 Answers

Let's evaluate each option:

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

    This means each individual file will be less cluttered, as requires 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.

  2. 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.

like image 52
Andrew Marshall Avatar answered Sep 28 '22 04:09

Andrew Marshall


For each file, require within that file all the files that it depends on. It does not harm to have duplicates with other files because each file is only required once. That is the purpose of the require method.

like image 21
sawa Avatar answered Sep 28 '22 03:09

sawa