Ruby module declaration

Is there a difference between doing

class Bus::Driver end 

and

 module Bus class Driver end end 

If not, which syntax is preferred?

+6
source share
3 answers

Is there any difference between doing [...]?

The only difference is that in class Bus::Driver , the Bus module must already be defined, while the same one is not worth it for the second.

Which syntax is preferable?

This is not a constructive question, but I personally prefer the second, because it clearly indicates that Bus is a module, and from the first I do not see at first glance if Bus is a module or class.

+7
source

This in itself:

 class Bus::Driver end 

will result in a NameError: uninitialized constant Bus error

So, at some point you need to declare a class Bus or module Bus . It does not have to be a complete hierarchy every time, though.

I tend to have an early requirement that sets namespaces and then uses a more concise form in the rest of my files. I don’t know that there is some kind of preferred approach - definitely nothing for which you are criticized.

+3
source

The first syntax is preferable when you have different module classes distributed over several files in a project; and provided that module always defined in PATH . For example, when creating gem .

The second is more central and should be done when it comes to details. module contains not only a class , but also includes methods and constants , etc. for namespace; which are useful.

+1
source

Source: https://habr.com/ru/post/944919/


All Articles