Sha256: 4c2f3032d6452f8e79841685c7aec3980a8ce122867027a69432dd359625876a

Contents?: true

Size: 1.73 KB

Versions: 7

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop checks for colons and commas in %i, e.g. `%i(:foo, :bar)`
      #
      # It is more likely that the additional characters are unintended (for
      # example, mistranslating an array of literals to percent string notation)
      # rather than meant to be part of the resulting symbols.
      #
      # @example
      #
      #   # bad
      #
      #   %i(:foo, :bar)
      #
      # @example
      #
      #   # good
      #
      #   %i(foo bar)
      class PercentSymbolArray < Base
        include PercentLiteral
        extend AutoCorrector

        MSG = "Within `%i`/`%I`, ':' and ',' are unnecessary and may be " \
          'unwanted in the resulting symbols.'

        def on_array(node)
          process(node, '%i', '%I')
        end

        def on_percent_literal(node)
          return unless contains_colons_or_commas?(node)

          add_offense(node) { |corrector| autocorrect(corrector, node) }
        end

        private

        def autocorrect(corrector, node)
          node.children.each do |child|
            range = child.loc.expression

            corrector.remove_trailing(range, 1) if range.source.end_with?(',')
            corrector.remove_leading(range, 1) if
              range.source.start_with?(':')
          end
        end

        def contains_colons_or_commas?(node)
          node.children.any? do |child|
            literal = child.children.first.to_s

            next if non_alphanumeric_literal?(literal)

            literal.start_with?(':') || literal.end_with?(',')
          end
        end

        def non_alphanumeric_literal?(literal)
          !/[[:alnum:]]/.match?(literal)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
rubocop-1.17.0 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-1.16.1 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-1.16.0 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-1.15.0 lib/rubocop/cop/lint/percent_symbol_array.rb
cocRb-0.1.0 .bundle/ruby/3.0.0/gems/rubocop-1.14.0/lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-1.14.0 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-1.13.0 lib/rubocop/cop/lint/percent_symbol_array.rb