class RuboCop::Cop::Performance::ConstantRegexp
end
@separators ||= /A#{SEPARATORS}Z/
def separators
# good
end
pattern.scan(TOKEN).reject { |token| token.match?(/A#{SEPARATORS}Z/o) }
def tokens(pattern)
# good
end
pattern.scan(TOKEN).reject { |token| token.match?(ALL_SEPARATORS) }
def tokens(pattern)
ALL_SEPARATORS = /A#{SEPARATORS}Z/
# good
end
pattern.scan(TOKEN).reject { |token| token.match?(/A#{SEPARATORS}Z/) }
def tokens(pattern)
# bad
@example
reuse that Regexp object.
memoize it, or add an ‘/o` option to perform `#{}` interpolation only once and
a regular expression. It is more efficient to extract it into a constant,
Ruby allocates a new Regexp object every time it executes a code containing such
Finds regular expressions with dynamic components that are all constants.
def self.autocorrect_incompatible_with
def self.autocorrect_incompatible_with [RegexpMatch] end
def include_interpolated_const?(node)
def include_interpolated_const?(node) return false unless node.interpolation? node.each_child_node(:begin).all? do |begin_node| inner_node = begin_node.children.first inner_node && (inner_node.const_type? || regexp_escape?(inner_node)) end end
def on_regexp(node)
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
def within_allowed_assignment?(node)
def within_allowed_assignment?(node) node.each_ancestor(:casgn, :or_asgn).any? end