Sha256: ebf7c0de35b433f7a54a7994d39132bf606ba9caf3755319b09f22cbc5d07c24

Contents?: true

Size: 1.55 KB

Versions: 11

Compression:

Stored size: 1.55 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.
      class PercentSymbolArray < Cop
        include PercentLiteral

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

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

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

          add_offense(node, :expression, MSG)
        end

        private

        def contains_colons_or_commas?(node)
          patterns = [/^:/, /,$/]
          node.children.any? do |child|
            literal = child.children.first

            # To avoid likely false positives (e.g. a single ' or ")
            next if literal.to_s.gsub(/[^\p{Alnum}]/, '').empty?

            patterns.any? { |pat| literal =~ pat }
          end
        end

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

              corrector.remove_trailing(range, 1) if /,$/ =~ range.source
              corrector.remove_leading(range, 1) if /^:/ =~ range.source
            end
          end
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-0.46.0 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-0.45.0 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-0.44.1 lib/rubocop/cop/lint/percent_symbol_array.rb
rubocop-0.44.0 lib/rubocop/cop/lint/percent_symbol_array.rb