lib/rubocop/cop/style/hash_syntax.rb in rubocop-0.14.1 vs lib/rubocop/cop/style/hash_syntax.rb in rubocop-0.15.0
- old
+ new
@@ -24,46 +24,57 @@
def ruby19_check(node)
pairs = *node
sym_indices = pairs.all? { |p| word_symbol_pair?(p) }
- if sym_indices
- pairs.each do |pair|
- if pair.loc.operator && pair.loc.operator.is?('=>')
- convention(pair,
- pair.loc.expression.begin.join(pair.loc.operator),
- MSG_19)
- end
- end
- end
+ check(pairs, '=>', MSG_19) if sym_indices
end
def hash_rockets_check(node)
pairs = *node
- pairs.each do |pair|
- if pair.loc.operator && pair.loc.operator.is?(':')
- convention(pair,
- pair.loc.expression.begin.join(pair.loc.operator),
- MSG_HASH_ROCKETS)
- end
- end
+ check(pairs, ':', MSG_HASH_ROCKETS)
end
def autocorrect(node)
+ key = node.children.first.loc.expression
+ op = node.loc.operator
+ if cop_config['EnforcedStyle'] == 'ruby19' &&
+ !space_before_operator?(op, key) &&
+ config.for_cop('SpaceAroundOperators')['Enabled']
+ # Don't do the correction if there is no space before '=>'. The
+ # combined corrections of this cop and SpaceAroundOperators could
+ # produce code with illegal syntax.
+ fail CorrectionNotPossible
+ end
+
@corrections << lambda do |corrector|
if cop_config['EnforcedStyle'] == 'ruby19'
- replacement = node.loc.expression.source[1..-1]
- .sub(/\s*=>\s*/, ': ')
+ corrector.insert_after(key, ' ')
+ corrector.replace(key, key.source.sub(/^:(.*)/, '\1:'))
else
- replacement = ':' + node.loc.expression.source
- .sub(/:\s*/, ' => ')
+ corrector.insert_after(key, ' => ')
+ corrector.insert_before(key, ':')
end
- corrector.replace(node.loc.expression, replacement)
+ corrector.remove(range_with_surrounding_space(op))
end
end
private
+
+ def space_before_operator?(op, key)
+ op.begin_pos - key.begin_pos - key.source.length > 0
+ end
+
+ def check(pairs, delim, msg)
+ pairs.each do |pair|
+ if pair.loc.operator && pair.loc.operator.is?(delim)
+ convention(pair,
+ pair.loc.expression.begin.join(pair.loc.operator),
+ msg)
+ end
+ end
+ end
def word_symbol_pair?(pair)
key, _value = *pair
if key.type == :sym