class RuboCop::Cop::Style::Not

This cop checks for uses of the keyword `not` instead of `!`.

@example

# bad - parentheses are required because of op precedence
x = (not something)

# good
x = !something

Constants

MSG
OPPOSITE_METHODS

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 36
def autocorrect(node)
  range = range_with_surrounding_space(range: node.loc.selector,
                                       side: :right)

  if opposite_method?(node.receiver)
    correct_opposite_method(range, node.receiver)
  elsif requires_parens?(node.receiver)
    correct_with_parens(range, node)
  else
    correct_without_parens(range)
  end
end
on_send(node) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 30
def on_send(node)
  return unless node.prefix_not?

  add_offense(node, location: :selector)
end

Private Instance Methods

correct_opposite_method(range, child) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 61
def correct_opposite_method(range, child)
  lambda do |corrector|
    corrector.remove(range)
    corrector.replace(child.loc.selector,
                      OPPOSITE_METHODS[child.method_name].to_s)
  end
end
correct_with_parens(range, node) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 69
def correct_with_parens(range, node)
  lambda do |corrector|
    corrector.replace(range, '!(')
    corrector.insert_after(node.source_range, ')')
  end
end
correct_without_parens(range) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 76
def correct_without_parens(range)
  ->(corrector) { corrector.replace(range, '!') }
end
opposite_method?(child) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 51
def opposite_method?(child)
  child.send_type? && OPPOSITE_METHODS.key?(child.method_name)
end
requires_parens?(child) click to toggle source
# File lib/rubocop/cop/style/not.rb, line 55
def requires_parens?(child)
  child.and_type? || child.or_type? ||
    child.send_type? && child.binary_operation? ||
    child.if_type? && child.ternary?
end