Skip to content

Commit

Permalink
[Fix rubocop#12291] Fix a false positive for Metrics/ClassLength
Browse files Browse the repository at this point in the history
Fixes rubocop#12291.

This PR fixes a false positive for `Metrics/ClassLength`
when a class with a singleton class definition.
  • Loading branch information
koic committed Oct 18, 2023
1 parent 6713311 commit 9eeb2f4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_a_false_positive_for_metrics_class_length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12291](https://github.com/rubocop/rubocop/issues/12291): Fix a false positive for `Metrics/ClassLength` when a class with a singleton class definition. ([@koic][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/metrics/class_length.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ class ClassLength < Base
def on_class(node)
check_code_length(node)
end
alias on_sclass on_class

def on_sclass(node)
return if node.each_ancestor(:class).any?

on_class(node)
end

def on_casgn(node)
parent = node.parent
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/metrics/class_length_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ class Test
RUBY
end

it 'registers an offense when a class with a singleton class definition has more than 5 lines' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [8/5]
class << self
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
end
RUBY
end

it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
class Test
Expand Down

0 comments on commit 9eeb2f4

Please sign in to comment.