I was looking at the Rubocop rule for module/class specification notations, and these two options exist:
# Style/ClassAndModuleChildren: EnforcedStyle: compact
module M::C
# Style/ClassAndModuleChildren: EnforcedStyle: nested
module M
class C
The following two files, when run, show that the two are not identical in behavior (see the end of each file for output results):
# nested.rb
# Style/ClassAndModuleChildren: EnforcedStyle: nested
module OuterModule
def foo; puts 'foo'; end
end
module OuterModule
module InnerModule
def hello
puts 'hello'
end
end
end
module OuterModule
class C
include InnerModule
end
end
# Does not produce any error when run
# compact.rb
# Style/ClassAndModuleChildren: EnforcedStyle: compact
module OuterModule
def foo; puts 'foo'; end
end
module OuterModule
module InnerModule
def hello
puts 'hello'
end
end
end
class OuterModule::C
include InnerModule
end
=begin
❯ ruby compact.rb
Traceback (most recent call last):
1: from compact.rb:15:in `<main>'
compact.rb:16:in `<class:C>': uninitialized constant OuterModule::C::InnerModule (NameError)
Did you mean? OuterModule::InnerModule
end
Why is this?
It is because of a process called constan lookup. When ruby encounters a constant token like InnerModule, it needs to find its assigned value. To do so, it checks the current "nesting" with Module.nesting.
nesting returns an array of modules we are currently nested in, but it can only be modified by keywords class and module (and has absolutely nothing to do with self, which might be a bit confusing). Each keyword prepends the module we're opening (and only that module) to the nesting:
Module.nesting #=> []
module A
class B
Module.nesting #=> [A::B, A]
end
end
module A::C
Module.nesting #=> [A::C] sic! no A
end
module A
D = Class.new do
Module.nesting #=> [A] sic! no module/class keyword = no nesting
end
end
So, when looking for any constant, ruby will search for them in the "namespaces" from Module.nesting and their's included modules (and, if nothing is found, in Object - which is Ruby's top namespace).
This is why
class OuterModule::C
include InnerModule
end
does not work. Ruby is only looking for InnerModule constant in OuterModule::C and global namespace.
It's also good to know, that new constants are always defined in the first namespace of Module.nesting - not self. This is quite common issue I see in RSpec tests:
RSpec.describe SomeClass do
EXAMPLES = [1,2,3,4,5]
...
end
Even though Rspec.describe creates a new class in which the given block is evaluated, there is no module/class keyword meaning that all the constants defined within that block are global. So if you've ever encounter a large dose of "already initialized constant/previous definition was here" when running a test, it is most likely because of that.