Skip to content

Commit

Permalink
[Fix #4124] Fix auto-correction with new line in Style/SymbolArray cop
Browse files Browse the repository at this point in the history
Bad code

```ruby
[
  :foo, :bar,
  :baz
]
```

Correction

```ruby
 # before
%i[foo bar baz]

 # after
%i[
  foo bar
  baz
]
```
  • Loading branch information
pocke authored and bbatsov committed Mar 19, 2017
1 parent 3da5bd9 commit 6c06bbb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 22 deletions.
32 changes: 10 additions & 22 deletions lib/rubocop/cop/style/symbol_array.rb
Expand Up @@ -12,6 +12,7 @@ module Style
class SymbolArray < Cop
include ConfigurableEnforcedStyle
include ArraySyntax
include PercentLiteral
extend TargetRubyVersion

minimum_target_ruby_version 2.0
Expand Down Expand Up @@ -59,32 +60,19 @@ def symbols_contain_spaces?(node)
end

def autocorrect(node)
syms = node.children.map { |c| c.children[0].to_s }
corrected = if style == :percent
percent_replacement(syms)
else
bracket_replacement(syms)
end

lambda do |corrector|
corrector.replace(node.source_range, corrected)
end
end

def percent_replacement(syms)
escape = syms.any? { |s| needs_escaping?(s) }
syms = syms.map { |s| escape_string(s) } if escape
syms = syms.map { |s| s.gsub(/\)/, '\\)') }
if escape
"%I(#{syms.join(' ')})"
if style == :percent
correct_percent(node, 'i')
else
"%i(#{syms.join(' ')})"
correct_bracketed(node)
end
end

def bracket_replacement(syms)
syms = syms.map { |s| to_symbol_literal(s) }
"[#{syms.join(', ')}]"
def correct_bracketed(node)
syms = node.children.map { |c| to_symbol_literal(c.children[0].to_s) }

lambda do |corrector|
corrector.replace(node.source_range, "[#{syms.join(', ')}]")
end
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/rubocop/cop/style/symbol_array_spec.rb
Expand Up @@ -17,6 +17,11 @@
expect(new_source).to eq('%i(one two three)')
end

it 'autocorrects arrays of symbols with new line' do
new_source = autocorrect_source(cop, "[:one,\n:two, :three,\n:four]")
expect(new_source).to eq("%i(one \ntwo three \nfour)")
end

it 'uses %I when appropriate' do
new_source = autocorrect_source(cop, '[:"\\t", :"\\n", :three]')
expect(new_source).to eq('%I(\\t \\n three)')
Expand Down

0 comments on commit 6c06bbb

Please sign in to comment.