Skip to content

Commit

Permalink
[Fix #9939] Fix/hash as last array item (#9943)
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Jaime committed Aug 19, 2021
1 parent 8e885c0 commit d9c2330
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/rubocop/cop/style/hash_as_last_array_item.rb
Expand Up @@ -29,6 +29,7 @@ module Style
# # good
# [{ one: 1 }, { two: 2 }]
class HashAsLastArrayItem < Base
include RangeHelp
include ConfigurableEnforcedStyle
extend AutoCorrector

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
49 changes: 49 additions & 0 deletions spec/rubocop/cop/style/hash_as_last_array_item_spec.rb
Expand Up @@ -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]
Expand Down

0 comments on commit d9c2330

Please sign in to comment.