Class: RuboCop::Cop::Elegant::ClassInModule

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/elegant/class_in_module.rb

Overview

Enforces that every class be defined inside a module. A class declared at the top level pollutes the global namespace and breaks modular design. The compact namespaced form class Foo::Bar is allowed because its name already resolves into an enclosing namespace, and so is a class nested inside another class, since the enclosing class names it too: class Foo::Bar; class Baz defines Foo::Bar::Baz. A class declared with an explicit root scope, class ::Baz, is global whatever encloses it lexically, so it is reported wherever it sits.

Constant Summary collapse

MSG =
'Class %<name>s must be defined inside a module, not globally'

Instance Method Summary collapse

Instance Method Details

#on_class(node) ⇒ Object



18
19
20
21
22
# File 'lib/rubocop/cop/elegant/class_in_module.rb', line 18

def on_class(node)
  return if namespaced?(node)
  return if scoped?(node)
  add_offense(node, message: format(MSG, name: label(node)))
end