2025-02-01 23:54:35 +00:00
|
|
|
# typed: strict
|
2024-01-26 13:47:59 -08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
|
|
|
module Homebrew
|
|
|
|
# Checks to make sure safe navigation isn't used with `blank?` in
|
|
|
|
# a conditional.
|
|
|
|
#
|
2024-04-26 20:55:51 +02:00
|
|
|
# NOTE: While the safe navigation operator is generally a good idea, when
|
|
|
|
# checking `foo&.blank?` in a conditional, `foo` being `nil` will actually
|
|
|
|
# do the opposite of what the author intends:
|
2024-01-26 13:47:59 -08:00
|
|
|
#
|
2024-04-26 20:55:51 +02:00
|
|
|
# ```ruby
|
|
|
|
# foo&.blank? #=> nil
|
|
|
|
# foo.blank? #=> true
|
|
|
|
# ```
|
2024-01-26 13:47:59 -08:00
|
|
|
#
|
2024-04-26 20:55:51 +02:00
|
|
|
# ### Example
|
2024-01-26 13:47:59 -08:00
|
|
|
#
|
2024-04-26 20:55:51 +02:00
|
|
|
# ```ruby
|
|
|
|
# # bad
|
|
|
|
# do_something if foo&.blank?
|
|
|
|
# do_something unless foo&.blank?
|
2024-01-26 13:47:59 -08:00
|
|
|
#
|
2024-04-26 20:55:51 +02:00
|
|
|
# # good
|
|
|
|
# do_something if foo.blank?
|
|
|
|
# do_something unless foo.blank?
|
|
|
|
# ```
|
2024-01-26 13:47:59 -08:00
|
|
|
class SafeNavigationWithBlank < Base
|
|
|
|
extend AutoCorrector
|
|
|
|
|
|
|
|
MSG = "Avoid calling `blank?` with the safe navigation operator in conditionals."
|
|
|
|
|
|
|
|
def_node_matcher :safe_navigation_blank_in_conditional?, <<~PATTERN
|
|
|
|
(if $(csend ... :blank?) ...)
|
|
|
|
PATTERN
|
|
|
|
|
2025-02-01 23:54:35 +00:00
|
|
|
sig { params(node: RuboCop::AST::IfNode).void }
|
2024-01-26 13:47:59 -08:00
|
|
|
def on_if(node)
|
|
|
|
return unless safe_navigation_blank_in_conditional?(node)
|
|
|
|
|
|
|
|
add_offense(node) do |corrector|
|
|
|
|
corrector.replace(safe_navigation_blank_in_conditional?(node).location.dot, ".")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|