Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Module Declaration [duplicate]

Tags:

ruby

Is there any difference between doing

class Bus::Driver
end

and

module Bus
  class Driver
  end
end

If not, which syntax is preferred?

like image 727
stuartrexking Avatar asked May 13 '13 19:05

stuartrexking


2 Answers

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

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

Which syntax is preferred?

This is not a constructive question but I personally prefer the second because it states explicitly that Bus is a module, while with the first I cannot see at first glance if Bus is a module or a class.

like image 112
Shoe Avatar answered Nov 02 '22 11:11

Shoe


This, on its own:

class Bus::Driver
end

will result in an error NameError: uninitialized constant Bus

So at some point you have to declare class Bus or module Bus. It doesn't have to be the full hierarchy each time though.

I tend to have an early require that sets up the namespaces, then use the more condensed form in the rest of my files. I'm not aware that there is any preferred approach - definitely nothing that you would be criticised for.

like image 3
Neil Slater Avatar answered Nov 02 '22 09:11

Neil Slater