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

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

Overview

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.'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.autocorrect_incompatible_withObject



41
42
43
# File 'lib/rubocop/cop/performance/constant_regexp.rb', line 41

def self.autocorrect_incompatible_with
  [RegexpMatch]
end

Instance Method Details

#on_regexp(node) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/rubocop/cop/performance/constant_regexp.rb', line 45

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