Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
Why do the compact and nested notations for classes/modules in Ruby behave differently?

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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda