Skip to content

Commit

Permalink
Merge pull request #8809 from pbernays/fix-style-for
Browse files Browse the repository at this point in the history
Fix multiple offense detection for Style/For
  • Loading branch information
koic committed Sep 30, 2020
2 parents 3fd227f + 2a13a6a commit e8cfbc1
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -9,6 +9,7 @@
### Bug fixes

* [#8810](https://github.com/rubocop-hq/rubocop/pull/8810): Fix multiple offense detection for Style/RaiseArgs. ([@pbernays][])
* [#8809](https://github.com/rubocop-hq/rubocop/pull/8809): Fix multiple offense detection for Style/For. ([@pbernays][])

### Changes

Expand Down
4 changes: 0 additions & 4 deletions lib/rubocop/cop/style/for.rb
Expand Up @@ -49,8 +49,6 @@ class For < Base

def on_for(node)
if style == :each
return unless opposite_style_detected

add_offense(node, message: PREFER_EACH) do |corrector|
ForToEachCorrector.new(node).call(corrector)
end
Expand All @@ -63,8 +61,6 @@ def on_block(node)
return unless suspect_enumerable?(node)

if style == :for
return unless opposite_style_detected

add_offense(node, message: PREFER_FOR) do |corrector|
EachToForCorrector.new(node).call(corrector)
end
Expand Down
56 changes: 56 additions & 0 deletions spec/rubocop/cop/style/for_spec.rb
Expand Up @@ -48,6 +48,34 @@ def func
RUBY
end

it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
[1, 2, 3].each do |n|
puts n
end
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
RUBY

expect_correction(<<~RUBY)
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
RUBY
end

context 'auto-correct' do
context 'with range' do
let(:expected_each_with_range) do
Expand Down Expand Up @@ -249,6 +277,34 @@ def func
RUBY
end

it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
RUBY

expect_correction(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
RUBY
end

it 'registers an offense for a tuple of items' do
expect_offense(<<~RUBY)
def func
Expand Down

0 comments on commit e8cfbc1

Please sign in to comment.