Sha256: 6777fbb1c5f9b6d1bbc069fb87b097aa0438af2451225e0a42c4308498b0fa0f

Contents?: true

Size: 1.84 KB

Versions: 10

Compression:

Stored size: 1.84 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop checks for quotes and commas in %w, e.g. `%w('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 strings.
      #
      # @example
      #
      #   # bad
      #
      #   %w('foo', "bar")
      #
      # @example
      #
      #   # good
      #
      #   %w(foo bar)
      class PercentStringArray < Base
        include PercentLiteral
        extend AutoCorrector

        QUOTES_AND_COMMAS = [/,$/, /^'.*'$/, /^".*"$/].freeze
        LEADING_QUOTE = /^['"]/.freeze
        TRAILING_QUOTE = /['"]?,?$/.freeze

        MSG = "Within `%w`/`%W`, quotes and ',' are unnecessary and may be " \
              'unwanted in the resulting strings.'

        def on_array(node)
          process(node, '%w', '%W')
        end

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

          add_offense(node) do |corrector|
            node.each_value do |value|
              range = value.loc.expression

              match = range.source.match(TRAILING_QUOTE)
              corrector.remove_trailing(range, match[0].length) if match

              corrector.remove_leading(range, 1) if LEADING_QUOTE.match?(range.source)
            end
          end
        end

        private

        def contains_quotes_or_commas?(node)
          node.values.any? do |value|
            literal = value.children.first.to_s.scrub

            # To avoid likely false positives (e.g. a single ' or ")
            next if literal.gsub(/[^[[:alnum:]]]/, '').empty?

            QUOTES_AND_COMMAS.any? { |pat| literal.match?(pat) }
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
rubocop-1.21.0 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.20.0 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.19.1 lib/rubocop/cop/lint/percent_string_array.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.19.0 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.18.4 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.18.3 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.18.2 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.18.1 lib/rubocop/cop/lint/percent_string_array.rb
rubocop-1.18.0 lib/rubocop/cop/lint/percent_string_array.rb