Sha256: 2c8eb20d802bb4f237ccf896be3fef0cac6a3d23c5c742deb9748a11966078d6

Contents?: true

Size: 1.2 KB

Versions: 13

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop checks to make sure safe navigation isn't used with `blank?` in
      # a conditional.
      #
      # 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.
      #
      # @example
      #   # 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

        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

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-rails-2.12.4 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.12.3 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.12.2 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.12.1 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.12.0 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.11.3 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.11.2 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.11.1 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.11.0 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.10.1 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.10.0 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.9.1 lib/rubocop/cop/rails/safe_navigation_with_blank.rb
rubocop-rails-2.9.0 lib/rubocop/cop/rails/safe_navigation_with_blank.rb