Sha256: 46016252ca824e3bd541833828b7d994068895441f4110dc96e4702b30582712

Contents?: true

Size: 922 Bytes

Versions: 4

Compression:

Stored size: 922 Bytes

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # Checks for uses of the character literal ?x.
      class CharacterLiteral < Cop
        include StringHelp

        MSG = 'Do not use the character literal - use string literal instead.'

        def offence?(node)
          # we don't register an offence for things like ?\C-\M-d
          node.loc.begin.is?('?') &&
            node.loc.expression.source.size.between?(2, 3)
        end

        def autocorrect(node)
          @corrections << lambda do |corrector|
            string = node.loc.expression.source[1..-1]

            if string.length == 1 # normal character
              corrector.replace(node.loc.expression, "'#{string}'")
            elsif string.length == 2 # special character like \n
              corrector.replace(node.loc.expression, %Q("#{string}"))
            end
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-0.16.0 lib/rubocop/cop/style/character_literal.rb
rubocop-0.15.0 lib/rubocop/cop/style/character_literal.rb
rubocop-0.14.1 lib/rubocop/cop/style/character_literal.rb
rubocop-0.14.0 lib/rubocop/cop/style/character_literal.rb