From d9c2330cfb64bf4777c253b58d5e3c71965fa726 Mon Sep 17 00:00:00 2001 From: Martin Jaime Date: Thu, 19 Aug 2021 02:34:59 -0300 Subject: [PATCH] [Fix #9939] Fix/hash as last array item (#9943) --- .../cop/style/hash_as_last_array_item.rb | 11 +++++ .../cop/style/hash_as_last_array_item_spec.rb | 49 +++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/lib/rubocop/cop/style/hash_as_last_array_item.rb b/lib/rubocop/cop/style/hash_as_last_array_item.rb index e8e7912d9b9..43ca432af7f 100644 --- a/lib/rubocop/cop/style/hash_as_last_array_item.rb +++ b/lib/rubocop/cop/style/hash_as_last_array_item.rb @@ -29,6 +29,7 @@ module Style # # good # [{ one: 1 }, { two: 2 }] class HashAsLastArrayItem < Base + include RangeHelp include ConfigurableEnforcedStyle extend AutoCorrector @@ -74,6 +75,7 @@ def check_no_braces(node) return if node.children.empty? # Empty hash cannot be "unbraced" add_offense(node, message: 'Omit the braces around the hash.') do |corrector| + remove_last_element_trailing_comma(corrector, node.parent) corrector.remove(node.loc.begin) corrector.remove(node.loc.end) end @@ -82,6 +84,15 @@ def check_no_braces(node) def braces_style? style == :braces end + + def remove_last_element_trailing_comma(corrector, node) + range = range_with_surrounding_space( + range: node.children.last.source_range, + side: :right + ).end.resize(1) + + corrector.remove(range) if range.source == ',' + end end end end diff --git a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb index 273d179f6aa..50518a661b1 100644 --- a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb +++ b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb @@ -54,6 +54,55 @@ RUBY end + it 'registers an offense and corrects when hash with braces and trailing comma' do + expect_offense(<<~RUBY) + [1, 2, { one: 1, two: 2, },] + ^^^^^^^^^^^^^^^^^^^ Omit the braces around the hash. + RUBY + + expect_correction(<<~RUBY) + [1, 2, one: 1, two: 2, ] + RUBY + end + + it 'registers an offense and corrects when hash with braces and trailing comma and new line' do + expect_offense(<<~RUBY) + [ + 1, + 2, + { + ^ Omit the braces around the hash. + one: 1, + two: 2, + }, + ] + RUBY + + expect_correction(<<~RUBY) + [ + 1, + 2, + #{' '} + one: 1, + two: 2, + #{' '} + ] + RUBY + end + + it 'does not register an offense when hash is not the last element' do + expect_no_offenses(<<~RUBY) + [ + 1, + 2, + { + one: 1 + }, + two: 2 + ] + RUBY + end + it 'does not register an offense when hash without braces' do expect_no_offenses(<<~RUBY) [1, 2, one: 1, two: 2]