Sha256: 8050657d0f2770033f664f1e795fef682f804428f3592462f71d769493593042

Contents?: true

Size: 1.52 KB

Versions: 6

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Checks for `:true` and `:false` symbols.
      # In most cases it would be a typo.
      #
      # @safety
      #   Autocorrection is unsafe for this cop because code relying
      #   on `:true` or `:false` symbols will break when those are
      #   changed to actual booleans.
      #
      # @example
      #
      #   # bad
      #   :true
      #
      #   # good
      #   true
      #
      #   # bad
      #   :false
      #
      #   # good
      #   false
      class BooleanSymbol < Base
        extend AutoCorrector

        MSG = 'Symbol with a boolean name - you probably meant to use `%<boolean>s`.'

        # @!method boolean_symbol?(node)
        def_node_matcher :boolean_symbol?, '(sym {:true :false})'

        def on_sym(node)
          return unless boolean_symbol?(node)

          parent = node.parent
          return if parent&.array_type? && parent.percent_literal?(:symbol)

          add_offense(node, message: format(MSG, boolean: node.value)) do |corrector|
            autocorrect(corrector, node)
          end
        end

        private

        def autocorrect(corrector, node)
          boolean_literal = node.source.delete(':')
          parent = node.parent
          if parent&.pair_type? && node.equal?(parent.children[0])
            corrector.remove(parent.loc.operator)
            boolean_literal = "#{node.source} =>"
          end

          corrector.replace(node, boolean_literal)
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-1.70.0 lib/rubocop/cop/lint/boolean_symbol.rb
rubocop-1.69.2 lib/rubocop/cop/lint/boolean_symbol.rb
rubocop-1.69.1 lib/rubocop/cop/lint/boolean_symbol.rb
rubocop-1.69.0 lib/rubocop/cop/lint/boolean_symbol.rb
rubocop-1.68.0 lib/rubocop/cop/lint/boolean_symbol.rb
rubocop-1.67.0 lib/rubocop/cop/lint/boolean_symbol.rb