Class: Hone::Patterns::StringDeletePrefix

Inherits:
Base
  • Object
show all
Defined in:
lib/hone/patterns/string_delete_prefix.rb

Overview

Pattern: str.sub(/^prefix/, '') -> str.delete_prefix('prefix')

delete_prefix is a specialized method that avoids the regex engine overhead. It's approximately 2x faster for this common use case.

Instance Attribute Summary

Attributes inherited from Base

#findings

Instance Method Summary collapse

Methods inherited from Base

#add_finding, inherited, #initialize, scan_file

Constructor Details

This class inherits a constructor from Hone::Patterns::Base

Instance Method Details

#visit_call_node(node) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/hone/patterns/string_delete_prefix.rb', line 13

def visit_call_node(node)
  super

  return unless node.name == :sub

  args = node.arguments&.arguments
  return unless args&.size == 2

  first_arg = args[0]
  second_arg = args[1]

  # Check if first arg is a regex starting with ^
  return unless first_arg.is_a?(Prism::RegularExpressionNode)
  return unless second_arg.is_a?(Prism::StringNode) && second_arg.content.empty?

  pattern = first_arg.content
  return unless pattern.start_with?("^")

  # Extract the literal prefix (after ^)
  prefix = pattern[1..]

  # Only suggest for simple literal prefixes (no regex metacharacters)
  return unless simple_literal?(prefix)

  add_finding(
    node,
    message: "Use `.delete_prefix('#{prefix}')` instead of `.sub(/^#{prefix}/, '')`",
    speedup: "Avoids regex engine overhead"
  )
end