Skip to content

Commit

Permalink
Support auto-correction in WordArray.
Browse files Browse the repository at this point in the history
Part of solution for rubocop#743.
  • Loading branch information
jonas054 committed Jan 26, 2014
1 parent f82a7d2 commit ebc6dee
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### New features

* [#714](https://github.com/bbatsov/rubocop/issues/714): New cop `RequireParentheses` checks for method calls without parentheses together with a boolean operator indicating that a mistake about precedence may have been made. ([@jonas054][])
* [#743](https://github.com/bbatsov/rubocop/issues/743): `WordArray` cop does auto-correction. ([@jonas054][])

### Changes

Expand Down
27 changes: 27 additions & 0 deletions lib/rubocop/cop/style/word_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,33 @@ def complex_content?(arr_sexp)
def min_size
cop_config['MinSize']
end

def autocorrect(node)
sb = node.loc.expression.source_buffer
interpolated = false

contents = node.children.map do |n|
if character_literal?(n)
interpolated = true
begin_pos = n.loc.expression.begin_pos + '?'.length
end_pos = n.loc.expression.end_pos
else
begin_pos = n.loc.begin.end_pos
end_pos = n.loc.end.begin_pos
end
Parser::Source::Range.new(sb, begin_pos, end_pos).source
end.join(' ')

char = interpolated ? 'W' : 'w'

@corrections << lambda do |corrector|
corrector.replace(node.loc.expression, "%#{char}(#{contents})")
end
end

def character_literal?(node)
node.loc.end.nil?
end
end
end
end
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/word_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,14 @@

expect(cop.offences.size).to eq(1)
end

it 'auto-corrects an array of words' do
new_source = autocorrect_source(cop, "['one', %q(two), 'three']")
expect(new_source).to eq('%w(one two three)')
end

it 'auto-corrects an array of words and character constants' do
new_source = autocorrect_source(cop, '[%{one}, %Q(two), ?\n, ?\t]')
expect(new_source).to eq('%W(one two \n \t)')
end
end

0 comments on commit ebc6dee

Please sign in to comment.