Skip to content

Commit

Permalink
Fix Metrics/PerceivedComplexity for case with else
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Jul 30, 2020
1 parent f24497f commit bb25e4b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/rubocop/cop/metrics/perceived_complexity.rb
Expand Up @@ -42,12 +42,13 @@ def complexity_score_for(node)
# If cond is nil, that means each when has an expression that
# evaluates to true or false. It's just an alternative to
# if/elsif/elsif... so the when nodes count.
nb_branches = node.when_branches.length + (node.else_branch ? 1 : 0)
if node.condition.nil?
node.when_branches.length
nb_branches
else
# Otherwise, the case node gets 0.8 complexity points and each
# when gets 0.2.
(0.8 + 0.2 * node.when_branches.length).round
(0.8 + 0.2 * nb_branches).round
end
when :if
node.else? && !node.elsif? ? 2 : 1
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/metrics/perceived_complexity_spec.rb
Expand Up @@ -156,6 +156,22 @@ def method_name
RUBY
end

it 'counts else in a case with no argument' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for method_name is too high. [4/1]
case
when value == 1
call_foo
when value == 2
call_bar
else
call_baz
end
end
RUBY
end

it 'registers an offense for &&' do
expect_offense(<<~RUBY)
def method_name
Expand Down

0 comments on commit bb25e4b

Please sign in to comment.