-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
interpolation_check.rb
53 lines (46 loc) · 1.45 KB
/
interpolation_check.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 Lint
# This cop checks for interpolation in a single quoted string.
#
# @example
#
# # bad
#
# foo = 'something with #{interpolation} inside'
#
# @example
#
# # good
#
# foo = "something with #{interpolation} inside"
class InterpolationCheck < Cop
MSG = 'Interpolation in single quoted string detected. '\
'Use double quoted strings if you need interpolation.'
def on_str(node)
return if heredoc?(node)
parent = node.parent
return if parent && (parent.dstr_type? || parent.regexp_type?)
return unless /(?<!\\)#\{.*\}/.match?(node.source.scrub)
add_offense(node)
end
def autocorrect(node)
lambda do |corrector|
starting_token, ending_token = if node.source.include?('"')
['%{', '}']
else
['"', '"']
end
corrector.replace(node.loc.begin, starting_token)
corrector.replace(node.loc.end, ending_token)
end
end
def heredoc?(node)
node.loc.is_a?(Parser::Source::Map::Heredoc) ||
(node.parent && heredoc?(node.parent))
end
end
end
end
end