Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #9767] Fix Style/ClassAndModuleChildren cop to preserve comments #9784

Merged
merged 1 commit into from May 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#9767](https://github.com/rubocop/rubocop/issues/9767): Fix `Style/ClassAndModuleChildren` cop to preserve comments. ([@tejasbubane][])
13 changes: 11 additions & 2 deletions lib/rubocop/cop/style/class_and_module_children.rb
Expand Up @@ -87,9 +87,18 @@ def compact_definition(corrector, node)
end

def compact_node(corrector, node)
replacement = "#{node.body.type} #{compact_identifier_name(node)}"
range = range_between(node.loc.keyword.begin_pos, node.body.loc.name.end_pos)
corrector.replace(range, replacement)
corrector.replace(range, compact_replacement(node))
end

def compact_replacement(node)
replacement = "#{node.body.type} #{compact_identifier_name(node)}"

body_comments = processed_source.ast_with_comments[node.body]
unless body_comments.empty?
replacement = body_comments.map(&:text).push(replacement).join("\n")
end
replacement
end

def compact_identifier_name(node)
Expand Down
40 changes: 40 additions & 0 deletions spec/rubocop/cop/style/class_and_module_children_spec.rb
Expand Up @@ -129,6 +129,23 @@ module Baz
RUBY
end

it 'preserves comments' do
expect_offense(<<~RUBY)
# top comment
class Foo::Bar # describe Foo::Bar
^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY

expect_correction(<<~RUBY)
# top comment
module Foo
class Bar # describe Foo::Bar
end
end
RUBY
end

it 'accepts nested children' do
expect_no_offenses(<<~RUBY)
class FooClass
Expand Down Expand Up @@ -251,6 +268,29 @@ module Foo::Bar::Baz
RUBY
end

it 'preserves comments between classes' do
expect_offense(<<~RUBY)
# describe Foo
# more Foo
class Foo
^^^ Use compact module/class definition instead of nested style.
# describe Bar
# more Bar
class Bar
end
end
RUBY

expect_correction(<<~RUBY)
# describe Foo
# more Foo
# describe Bar
# more Bar
class Foo::Bar
end
RUBY
end

it 'accepts compact style for classes/modules' do
expect_no_offenses(<<~RUBY)
class FooClass::BarClass
Expand Down