This might be a bit of an esoteric question, but I just want to know what best practices are on this issue.
You should refrain from doing so, unless you have a good reason. One file with several small related classes can be more readable than several files.
include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.
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' .
In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.
Yes, it is generally acceptable because it doesn't violate any principles of the Ruby language itself but it ultimately depends on the practices of your target audience or framework. (For example, Rails likes your classes to be one-per-file.)
However, if you are grouping classes with related functionality into a single file then you should also consider making them part of the same module for a namespace.
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