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?
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.
Ruby looks in all the paths specified in the $LOAD_PATH array.
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' .
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.
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.
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