Skip to content

Commit

Permalink
Make Lint/RedundantWithIndex cop aware of offset argument
Browse files Browse the repository at this point in the history
Follow up of rubocop#4796 (comment).

Actually, it is only `with_index` method that accepts an offset argument.
`with_with_index` method doesn't accept offset argument.
However, I think that the same AST will be low maintenance cost.
  • Loading branch information
koic committed Nov 1, 2017
1 parent af630aa commit 1bfb387
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

* [#4888](https://github.com/bbatsov/rubocop/pull/4888): Improve offense message of `Style/StderrPuts`. ([@jaredbeck][])
* [#4886](https://github.com/bbatsov/rubocop/issues/4886): Fix false offense for Style/CommentedKeyword. ([@michniewicz][])
* [#4977](https://github.com/bbatsov/rubocop/pull/4977): Make `Lint/RedundantWithIndex` cop aware of offset argument. ([@koic][])

### New features

Expand Down
6 changes: 3 additions & 3 deletions lib/rubocop/cop/lint/redundant_with_index.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class RedundantWithIndex < Cop
def_node_matcher :redundant_with_index?, <<-PATTERN
(block
$(send
_ {:each_with_index :with_index})
_ {:each_with_index :with_index} ...)
(args
(arg _))
...)
Expand All @@ -51,7 +51,7 @@ def autocorrect(node)
if send.method_name == :each_with_index
corrector.replace(send.loc.selector, 'each')
else
corrector.remove(send.loc.selector)
corrector.remove(with_index_range(send))
corrector.remove(send.loc.dot)
end
end
Expand All @@ -69,7 +69,7 @@ def message(node)
end

def with_index_range(send)
range_between(send.loc.selector.begin_pos, send.loc.selector.end_pos)
range_between(send.loc.selector.begin_pos, send.source.length)
end
end
end
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/lint/redundant_with_index_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
RUBY
end

it 'registers an offense when using `ary.each.with_index(1) { |v| v }`' do
expect_offense(<<-RUBY.strip_indent)
ary.each.with_index(1) { |v| v }
^^^^^^^^^^^^^ Remove redundant `with_index`.
RUBY
end

it 'registers an offense when using `ary.each_with_object([]).with_index ' \
'{ |v| v }`' do
expect_offense(<<-RUBY.strip_indent)
Expand All @@ -39,6 +46,12 @@
expect(new_source).to eq 'ary.each { |v| v }'
end

it 'autocorrects to ary.each from ary.each.with_index(1)' do
new_source = autocorrect_source('ary.each.with_index(1) { |v| v }')

expect(new_source).to eq 'ary.each { |v| v }'
end

it 'autocorrects to ary.each from ary.each_with_object([]).with_index' do
new_source = autocorrect_source('ary.each_with_object([]) { |v| v }')

Expand Down

0 comments on commit 1bfb387

Please sign in to comment.