lib/rubocop/cop/style/negated_if.rb in rubocop-0.20.0 vs lib/rubocop/cop/style/negated_if.rb in rubocop-0.20.1
- old
+ new
@@ -6,28 +6,37 @@
# Checks for uses of if with a negated condition. Only ifs
# without else are considered.
class NegatedIf < Cop
include NegativeConditional
+ MSG = 'Favor `%s` over `%s` for negative conditions.'
+
def on_if(node)
return unless node.loc.respond_to?(:keyword)
return if node.loc.keyword.is?('elsif')
check(node)
end
- def error_message
- 'Favor `unless` over `if` for negative conditions.'
+ def message(node)
+ if node.loc.keyword.is?('if')
+ format(MSG, 'unless', 'if')
+ else
+ format(MSG, 'if', 'unless')
+ end
end
private
def autocorrect(node)
@corrections << lambda do |corrector|
condition, _body, _rest = *node
# unwrap the negated portion of the condition (a send node)
pos_condition, _method, = *condition
- corrector.replace(node.loc.keyword, 'unless')
+ corrector.replace(
+ node.loc.keyword,
+ node.loc.keyword.is?('if') ? 'unless' : 'if'
+ )
corrector.replace(condition.loc.expression,
pos_condition.loc.expression.source)
end
end
end