From 8f0047957aa211b8d3e5730596f084de3c07d73b Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Mon, 3 May 2021 14:56:53 -0400 Subject: [PATCH] [Fix #9762] Update `VariableForce` to be able to handle `case-match` nodes. --- .../fix_update_variableforce_to_be_able_to.md | 1 + lib/rubocop/cop/variable_force/branch.rb | 15 +++++++++++++++ spec/rubocop/cop/lint/useless_assignment_spec.rb | 15 +++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 changelog/fix_update_variableforce_to_be_able_to.md diff --git a/changelog/fix_update_variableforce_to_be_able_to.md b/changelog/fix_update_variableforce_to_be_able_to.md new file mode 100644 index 00000000000..301c40a3d35 --- /dev/null +++ b/changelog/fix_update_variableforce_to_be_able_to.md @@ -0,0 +1 @@ +* [#9762](https://github.com/rubocop/rubocop/issues/9762): Update `VariableForce` to be able to handle `case-match` nodes. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/variable_force/branch.rb b/lib/rubocop/cop/variable_force/branch.rb index e66a38438d7..ffc3eb72bb3 100644 --- a/lib/rubocop/cop/variable_force/branch.rb +++ b/lib/rubocop/cop/variable_force/branch.rb @@ -226,6 +226,21 @@ def always_run? end end + # case target + # in pattern # in_pattern + # else + # else_body + # end + class CaseMatch < Base + define_predicate :target?, child_index: 0 + define_predicate :in_pattern?, child_index: 1..-2 + define_predicate :else_body?, child_index: -1 + + def always_run? + target? + end + end + # for element in collection # loop_body # end diff --git a/spec/rubocop/cop/lint/useless_assignment_spec.rb b/spec/rubocop/cop/lint/useless_assignment_spec.rb index d3e6245742b..b0e0ee29e9b 100644 --- a/spec/rubocop/cop/lint/useless_assignment_spec.rb +++ b/spec/rubocop/cop/lint/useless_assignment_spec.rb @@ -1416,4 +1416,19 @@ def some_method(environment) end end end + + context 'inside a `case-match` node', :ruby27 do + it 'does not register an offense when the variable is used' do + expect_no_offenses(<<~RUBY) + case '0' + in String + res = 1 + else + res = 2 + end + + do_something(res) + RUBY + end + end end