Sha256: 1dacac1c24b9bcce9a4684ce2f256fe469878aab957d8a70ae22a7ef90808cf7

Contents?: true

Size: 1.39 KB

Versions: 7

Compression:

Stored size: 1.39 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks for usage of the %Q() syntax when %q() would do.
      class PercentQLiterals < Cop
        include PercentLiteral
        include ConfigurableEnforcedStyle

        def on_str(node)
          process(node, '%Q', '%q')
        end

        private

        def on_percent_literal(node)
          if style == :lower_case_q
            if type(node) == '%Q'
              check(node,
                    'Do not use `%Q` unless interpolation is needed.  ' \
                    'Use `%q`.')
            end
          elsif type(node) == '%q'
            check(node, 'Use `%Q` instead of `%q`.')
          end
        end

        def check(node, msg)
          src = node.loc.expression.source
          # Report offense only if changing case doesn't change semantics,
          # i.e., if the string would become dynamic or has special characters.
          return if node.children !=
                    ProcessedSource.new(corrected(src)).ast.children

          add_offense(node, :begin, msg)
        end

        def autocorrect(node)
          src = node.loc.expression.source

          @corrections << lambda do |corrector|
            corrector.replace(node.loc.expression, corrected(src))
          end
        end

        def corrected(src)
          src.sub(src[1], src[1].swapcase)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rubocop-0.30.1 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.30.0 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.29.1 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.29.0 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.28.0 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.27.1 lib/rubocop/cop/style/percent_q_literals.rb
rubocop-0.27.0 lib/rubocop/cop/style/percent_q_literals.rb