class RuboCop::Cop::Style::ExactRegexpMatch

Checks for exact regexp match inside Regexp literals.

@example

# bad
string =~ /\Astring\z/
string === /\Astring\z/
string.match(/\Astring\z/)
string.match?(/\Astring\z/)

# good
string == 'string'

# bad
string !~ /\Astring\z/

# good
string != 'string'

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_csend(node)
Alias for: on_send
on_send(node) click to toggle source
# File lib/rubocop/cop/style/exact_regexp_match.rb, line 40
def on_send(node)
  return unless (receiver = node.receiver)
  return unless (regexp = exact_regexp_match(node))

  parsed_regexp = Regexp::Parser.parse(regexp)
  return unless exact_match_pattern?(parsed_regexp)

  prefer = "#{receiver.source} #{new_method(node)} '#{parsed_regexp[1].text}'"

  add_offense(node, message: format(MSG, prefer: prefer)) do |corrector|
    corrector.replace(node, prefer)
  end
end
Also aliased as: on_csend

Private Instance Methods

exact_match_pattern?(parsed_regexp) click to toggle source
# File lib/rubocop/cop/style/exact_regexp_match.rb, line 57
def exact_match_pattern?(parsed_regexp)
  tokens = parsed_regexp.map(&:token)
  return false unless tokens[0] == :bos && tokens[1] == :literal && tokens[2] == :eos

  !parsed_regexp[1].quantifier
end
new_method(node) click to toggle source
# File lib/rubocop/cop/style/exact_regexp_match.rb, line 64
def new_method(node)
  node.method?(:!~) ? '!=' : '=='
end