Skip to content

Commit

Permalink
[Fix rubocop#9767] Fix Style/ClassAndModuleChildren cop to preserve…
Browse files Browse the repository at this point in the history
… comments

Closes rubocop#9767
  • Loading branch information
tejasbubane committed May 7, 2021
1 parent 7be423a commit 10db3f2
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
@@ -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

0 comments on commit 10db3f2

Please sign in to comment.