brew/Library/Homebrew/rubocops/safe_navigation_with_blank.rb
Issy Long 0fc1eb534b
More Sorbet typed: strict RuboCops
- Some of these I bumped to `typed: strict`, some of them I added
  intermediary type signatures to some of the methods to make my life
  easier in the (near, hopefully) future.
- Turns out that RuboCop node matchers that end in `?`
  can return `nil` if they don't match anything, not `false`.
2025-02-08 23:38:12 +00:00

51 lines
1.4 KiB
Ruby

# typed: strict
# frozen_string_literal: true
module RuboCop
module Cop
module Homebrew
# Checks to make sure safe navigation isn't used with `blank?` in
# a conditional.
#
# 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:
#
# ```ruby
# foo&.blank? #=> nil
# foo.blank? #=> true
# ```
#
# ### Example
#
# ```ruby
# # bad
# do_something if foo&.blank?
# do_something unless foo&.blank?
#
# # good
# do_something if foo.blank?
# do_something unless foo.blank?
# ```
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
sig { params(node: RuboCop::AST::IfNode).void }
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