/
character_literal.rb
53 lines (46 loc) · 1.37 KB
/
character_literal.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of the character literal ?x.
#
# @example
# # bad
# ?x
#
# # good
# 'x'
#
# # good
# ?\C-\M-d
class CharacterLiteral < Cop
include StringHelp
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(node)
lambda do |corrector|
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
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