Meena MK
Meena MK

Reputation: 11

difference between modules inside a class and class inside a modules in ruby

I think both are used for namespace. Modules are generally mixed into classes, right? So, what would be the purpose of defining a module inside a class?

Upvotes: 1

Views: 484

Answers (1)

ndnenkov
ndnenkov

Reputation: 36101

Generally speaking modules have two uses:

  • Namespacing modules. When you nest stuff here and the module is intended only for specifying paths.
  • Functional modules. When the module has actual functionality that is intended to be called directly on the module or the module is intended to be included/extended.

Classes should be used for functionality only, even though Ruby doesn't enforce it.

Trying to do something but the above (like use module for both namespacing and functionality (1) or use a class for namespacing (2)) will generally confuse you.


(1) Some will disagree pointing to the rails' module with instance methods that also holds another module, called ClassMethods. I think it would have been cleaner if there was a module with two modules - ClassMethods and InstanceMethods instead.

(2) Some will disagree. A probably valid case is if you try to emulate private classes from other languages (where the private class will be nested inside your public class).

Upvotes: 1

Related Questions