Class: Rubocop::Cop::Style::CharacterLiteral

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/style/character_literal.rb

Overview

Checks for uses of the character literal ?x.

Constant Summary collapse

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

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #corrections, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, all, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#autocorrect_action(node) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rubocop/cop/style/character_literal.rb', line 27

def autocorrect_action(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

#on_str(node) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rubocop/cop/style/character_literal.rb', line 10

def on_str(node)
  # Constants like __FILE__ are handled as strings,
  # but don't respond to begin.
  return unless node.loc.respond_to?(:begin) && node.loc.begin
  return if part_of_ignored_node?(node)

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