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, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

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

Constructor Details

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

Instance Method Details

#autocorrect_action(node) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/rubocop/cop/style/character_literal.rb', line 25

def autocorrect_action(node)
  string = node.loc.expression.source[1..-1]

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

#on_str(node) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# 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)

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