Sha256: 488c56adf6c0fd3729740b98c14718e598ca3fa2bf06c5c877255957417fa1b3

Contents?: true

Size: 1.7 KB

Versions: 14

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for uses of the character literal ?x.
      # Starting with Ruby 1.9 character literals are
      # essentially one-character strings, so this syntax
      # is mostly redundant at this point.
      #
      # ? character literal can be used to express meta and control character.
      # That's a good use case of ? literal so it doesn't count it as an offense.
      #
      # @example
      #   # bad
      #   ?x
      #
      #   # good
      #   'x'
      #
      #   # good - control & meta escapes
      #   ?\C-\M-d
      #   "\C-\M-d" # same as above
      class CharacterLiteral < Base
        include StringHelp
        extend AutoCorrector

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

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

        def autocorrect(corrector, node)
          string = node.source[1..-1]

          # special character like \n
          # or ' which needs to use "" or be escaped.
          if string.length == 2 || string == "'"
            corrector.replace(node, %("#{string}"))
          elsif string.length == 1 # normal character
            corrector.replace(node, "'#{string}'")
          end
        end

        # Dummy implementation of method in ConfigurableEnforcedStyle that is
        # called from StringHelp.
        def opposite_style_detected; end

        # Dummy implementation of method in ConfigurableEnforcedStyle that is
        # called from StringHelp.
        def correct_style_detected; end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 4 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/character_literal.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/character_literal.rb
rubocop-1.28.2 lib/rubocop/cop/style/character_literal.rb
rubocop-1.28.1 lib/rubocop/cop/style/character_literal.rb
rubocop-1.28.0 lib/rubocop/cop/style/character_literal.rb
rubocop-1.27.0 lib/rubocop/cop/style/character_literal.rb
rubocop-1.26.1 lib/rubocop/cop/style/character_literal.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/character_literal.rb
rubocop-1.26.0 lib/rubocop/cop/style/character_literal.rb
rubocop-1.25.1 lib/rubocop/cop/style/character_literal.rb
rubocop-1.25.0 lib/rubocop/cop/style/character_literal.rb
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/style/character_literal.rb
rubocop-1.24.1 lib/rubocop/cop/style/character_literal.rb
rubocop-1.24.0 lib/rubocop/cop/style/character_literal.rb