class RuboCop::Cop::Rouge::NoBuildingAlternationPatternInRegexp
Checks for the use of β.join(β|β)` or `Regexp.union` inside interpolated regular expressions.
Building alternation patterns by joining arrays or using βRegexp.union` inside a regexp harms performance β the regex engine must backtrack through every alternative on each match attempt. It also risks quoting bugs when values contain regex metacharacters.
Prefer a βSet` lookup with a simple regex pattern instead.
@example
# bad β joins an array into a huge alternation regex KEYWORDS = %w[if else while ...] rule %r/\b(#{KEYWORDS.join('|')})\b/, Keyword # bad β Regexp.union inside a regex has the same problem rule %r/#{Regexp.union(keywords)}/ # good β simple regex + Set lookup KEYWORDS = Set.new(%w[if else while ...]) rule %r/\w+/ do |m| if KEYWORDS.include?(m[0]) token Keyword else token Name end end
Constants
- MSG
Public Instance Methods
Source
# File lib/rubocop/cop/rouge/no_building_alternation_pattern_in_regexp.rb, line 51 def on_regexp(node) node.children.each do |child| next unless child.begin_type? find_offending_calls(child) end end
Private Instance Methods
Source
# File lib/rubocop/cop/rouge/no_building_alternation_pattern_in_regexp.rb, line 61 def find_offending_calls(begin_node) begin_node.each_descendant(:send) do |send_node| next unless join_pipe_call?(send_node) || regexp_union_call?(send_node) add_offense(send_node) end end