forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsquished_sql_heredocs.rb
82 lines (73 loc) · 1.83 KB
/
squished_sql_heredocs.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
#
# Checks SQL heredocs to use `.squish`.
# Some SQL syntax (e.g. PostgreSQL comments and functions) requires newlines
# to be preserved in order to work, thus auto-correction for this cop is not safe.
#
# @example
# # bad
# <<-SQL
# SELECT * FROM posts;
# SQL
#
# <<-SQL
# SELECT * FROM posts
# WHERE id = 1
# SQL
#
# execute(<<~SQL, "Post Load")
# SELECT * FROM posts
# WHERE post_id = 1
# SQL
#
# # good
# <<-SQL.squish
# SELECT * FROM posts;
# SQL
#
# <<~SQL.squish
# SELECT * FROM table
# WHERE id = 1
# SQL
#
# execute(<<~SQL.squish, "Post Load")
# SELECT * FROM posts
# WHERE post_id = 1
# SQL
#
class SquishedSQLHeredocs < Base
include Heredoc
extend AutoCorrector
SQL = 'SQL'
SQUISH = '.squish'
MSG = 'Use `%<expect>s` instead of `%<current>s`.'
def on_heredoc(node)
return unless offense_detected?(node)
add_offense(node) do |corrector|
corrector.insert_after(node, SQUISH)
end
end
private
def offense_detected?(node)
sql_heredoc?(node) && !using_squish?(node)
end
def sql_heredoc?(node)
delimiter_string(node) == SQL
end
def using_squish?(node)
node.parent&.send_type? && node.parent&.method?(:squish)
end
def message(node)
format(
MSG,
expect: "#{node.source}#{SQUISH}",
current: node.source
)
end
end
end
end
end