From c5fd6ed866dc0656fbe3d8d00aca4a7d0b9b79d6 Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Sun, 18 Apr 2021 15:10:45 -0400 Subject: [PATCH] [Fix #9689] Treat parens around array items the same for children and deeper descendants. --- ...treat_parens_around_array_items_the_same.md | 1 + lib/rubocop/cop/style/redundant_parentheses.rb | 10 +++------- .../cop/style/redundant_parentheses_spec.rb | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 7 deletions(-) create mode 100644 changelog/fix_treat_parens_around_array_items_the_same.md diff --git a/changelog/fix_treat_parens_around_array_items_the_same.md b/changelog/fix_treat_parens_around_array_items_the_same.md new file mode 100644 index 00000000000..0ed73f6aeb6 --- /dev/null +++ b/changelog/fix_treat_parens_around_array_items_the_same.md @@ -0,0 +1 @@ +* [#9689](https://github.com/rubocop/rubocop/issues/9689): Treat parens around array items the same for children and deeper descendants. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/style/redundant_parentheses.rb b/lib/rubocop/cop/style/redundant_parentheses.rb index 59492354396..56f2351d3e7 100644 --- a/lib/rubocop/cop/style/redundant_parentheses.rb +++ b/lib/rubocop/cop/style/redundant_parentheses.rb @@ -158,15 +158,11 @@ def allowed_array_or_hash_element?(node) # { a: (1 # ), } # ``` - (hash_element?(node) || array_element?(node)) && only_closing_paren_before_comma?(node) + hash_or_array_element?(node) && only_closing_paren_before_comma?(node) end - def hash_element?(node) - node.parent&.pair_type? - end - - def array_element?(node) - node.parent&.array_type? + def hash_or_array_element?(node) + node.each_ancestor(:array, :hash).any? end def only_closing_paren_before_comma?(node) diff --git a/spec/rubocop/cop/style/redundant_parentheses_spec.rb b/spec/rubocop/cop/style/redundant_parentheses_spec.rb index 7abe0344b25..dc7f613acb9 100644 --- a/spec/rubocop/cop/style/redundant_parentheses_spec.rb +++ b/spec/rubocop/cop/style/redundant_parentheses_spec.rb @@ -162,6 +162,24 @@ it_behaves_like 'plausible', "[(1\n),]" + it_behaves_like 'plausible', <<~RUBY + [ + ( + 1 + ), + 2 + ] + RUBY + + it_behaves_like 'plausible', <<~RUBY + [ + x = ( + 1 + ), + y = 2 + ] + RUBY + it 'registers an offense for parens around a literal hash value' do expect_offense(<<~RUBY) {a: (1)}