Class: Hone::Patterns::StringCasecmp

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

Overview

Pattern: str.downcase == other.downcase -> str.casecmp?(other)

casecmp? performs case-insensitive comparison without creating intermediate lowercase/uppercase strings, reducing allocations.

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
# File 'lib/hone/patterns/string_casecmp.rb', line 13

def visit_call_node(node)
  super

  return unless node.name == :==

  # The receiver should be a call to downcase or upcase
  receiver = node.receiver
  return unless case_conversion_call?(receiver)

  # The argument should also be a call to downcase or upcase
  args = node.arguments&.arguments
  return unless args&.size == 1

  arg = args[0]
  return unless case_conversion_call?(arg)

  # Both should use the same case conversion method
  receiver_method = receiver.name
  arg_method = arg.name
  return unless receiver_method == arg_method

  method_name = (receiver_method == :downcase) ? "downcase" : "upcase"

  add_finding(
    node,
    message: "Use `.casecmp?(other)` instead of `.#{method_name} == other.#{method_name}`",
    speedup: "Avoids creating intermediate lowercase strings"
  )
end