Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: is it acceptable to put more than one class in a file?

This might be a bit of an esoteric question, but I just want to know what best practices are on this issue.

like image 979
jaydel Avatar asked Jun 22 '11 12:06

jaydel


People also ask

Is it good practice to have multiple classes in a file?

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.

Can we include class in Ruby?

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.

How do you call a class from a different file 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' .

What happens when you require a file in Ruby?

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.


1 Answers

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.

like image 121
maerics Avatar answered Oct 27 '22 23:10

maerics