Class: RuboCop::Cop::Performance::ConstantRegexp

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/performance/constant_regexp.rb

Overview

This cop finds regular expressions with dynamic components that are all constants.

Ruby allocates a new Regexp object every time it executes a code containing such a regular expression. It is more efficient to extract it into a constant, memoize it, or add an `/o` option to perform `#{}` interpolation only once and reuse that Regexp object.

Examples:


# bad
def tokens(pattern)
  pattern.scan(TOKEN).reject { |token| token.match?(/\A#{SEPARATORS}\Z/) }
end

# good
ALL_SEPARATORS = /\A#{SEPARATORS}\Z/
def tokens(pattern)
  pattern.scan(TOKEN).reject { |token| token.match?(ALL_SEPARATORS) }
end

# good
def tokens(pattern)
  pattern.scan(TOKEN).reject { |token| token.match?(/\A#{SEPARATORS}\Z/o) }
end

# good
def separators
  @separators ||= /\A#{SEPARATORS}\Z/
end

Constant Summary collapse

MSG =
'Extract this regexp into a constant, memoize it, or append an `/o` option to its options.'

Instance Method Summary collapse

Instance Method Details

#on_regexp(node) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/performance/constant_regexp.rb', line 41

def on_regexp(node)
  return if within_allowed_assignment?(node) ||
            !include_interpolated_const?(node) ||
            node.single_interpolation?

  add_offense(node) do |corrector|
    corrector.insert_after(node, 'o')
  end
end