Skip to content

Style/ClassAndModuleChildren not safe within module or class #14476

@headius

Description

@headius

The Style/ClassAndModuleChildren cop is not safe to correct when the code occurs within another scope. This led to a bug in JRuby's build when using automated corrections.

Nested module access will not walk up to the toplevel to look for modules or classes to open, while path-based access does do this.


Expected behavior

Code below should behave this way before or after correction, or else it should be considered an unsafe correction.

Original code:

module X
  module Y
    puts object_id
  end
end
module Z
  module X::Y
    puts object_id
  end
end
# prints same object id for Y, because path-based access uses the toplevel X
# and reopens the existing modules

Actual behavior

When corrected to nested modules, the reopen of X creates a new module tree rather than accessing the toplevel X.

Corrected code:

...
module Z
  module X
    module Y
      puts object_id
    end
  end
end
# Reopen of X is a new module and Y is also new with a different object_id

Full script example of the behavior:

module X
  module Y
    puts object_id
  end
end
module Z
  module X::Y
    puts object_id
  end
end
module Q
  module X
    module Y
      puts object_id
    end
  end
end

Output from example, showing that the correction is not safe:

$ cx 3.4 ruby -v blah.rb
ruby 3.4.5 (2025-07-16 revision 20cda200d3) +PRISM [arm64-darwin24]
16
16
24

RuboCop version

$ rubocop -V
1.80.0 (using Parser 3.3.9.0, rubocop-ast 1.46.0, analyzing as Ruby 2.7, running on jruby 3.1.7) [java]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions