Skip to content

Commit

Permalink
Fix Style/ClassAndModuleChildren compaction for oneliner children
Browse files Browse the repository at this point in the history
Signed-off-by: Alexandre Terrasa <alexandre.terrasa@shopify.com>
  • Loading branch information
Morriar committed Jul 13, 2022
1 parent 0562314 commit 2bb5782
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_style_class_and_module_children.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Fix Style/ClassAndModuleChildren compaction for oneliner children. ([@Morriar][])
11 changes: 7 additions & 4 deletions lib/rubocop/cop/style/class_and_module_children.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,16 @@ def compact_identifier_name(node)
end

def remove_end(corrector, body)
range = range_between(
body.loc.end.begin_pos - leading_spaces(body).size,
body.loc.end.end_pos + 1
)
begin_pos = body.loc.end.begin_pos
begin_pos -= leading_spaces(body).size unless oneline?(body)
range = range_between(begin_pos, body.loc.end.end_pos + 1)
corrector.remove(range)
end

def oneline?(node)
node.loc.name.line == node.loc.end.line
end

def configured_indentation_width
config.for_badge(Layout::IndentationWidth.badge).fetch('Width', 2)
end
Expand Down
36 changes: 36 additions & 0 deletions spec/rubocop/cop/style/class_and_module_children_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,24 @@ class FooClass::BarClass
RUBY
end

it 'registers a offense for classes with nested oneline children' do
expect_offense(<<~RUBY)
class FooClass
^^^^^^^^ Use compact module/class definition instead of nested style.
class BarClass end
end
class FooClass
^^^^^^^^ Use compact module/class definition instead of nested style.
class BarClass; end
end
RUBY

expect_correction(<<~RUBY)
class FooClass::BarClass end
class FooClass::BarClass; end
RUBY
end

it 'registers a offense for modules with nested children' do
expect_offense(<<~RUBY)
module FooModule
Expand All @@ -224,6 +242,24 @@ def method_example
RUBY
end

it 'registers a offense for modules with nested oneline children' do
expect_offense(<<~RUBY)
module FooModule
^^^^^^^^^ Use compact module/class definition instead of nested style.
module BarModule end
end
module FooModule
^^^^^^^^^ Use compact module/class definition instead of nested style.
module BarModule; end
end
RUBY

expect_correction(<<~RUBY)
module FooModule::BarModule end
module FooModule::BarModule; end
RUBY
end

it 'correctly indents heavily nested children' do
expect_offense(<<~RUBY)
module FooModule
Expand Down

0 comments on commit 2bb5782

Please sign in to comment.