forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.rb
66 lines (56 loc) · 1.65 KB
/
output.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop checks for the use of output calls like puts and print
#
# @example
# # bad
# puts 'A debug message'
# pp 'A debug message'
# print 'A debug message'
#
# # good
# Rails.logger.debug 'A debug message'
class Output < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not write to stdout. ' \
"Use Rails's logger if you want to log."
RESTRICT_ON_SEND = %i[
ap p pp pretty_print print puts binwrite syswrite write write_nonblock
].freeze
def_node_matcher :output?, <<~PATTERN
(send nil? {:ap :p :pp :pretty_print :print :puts} ...)
PATTERN
def_node_matcher :io_output?, <<~PATTERN
(send
{
(gvar #match_gvar?)
{(const nil? :STDOUT) (const nil? :STDERR)}
}
{:binwrite :syswrite :write :write_nonblock}
...)
PATTERN
def on_send(node)
return unless (output?(node) || io_output?(node)) && node.arguments?
range = offense_range(node)
add_offense(range) do |corrector|
corrector.replace(range, 'Rails.logger.debug')
end
end
private
def match_gvar?(sym)
%i[$stdout $stderr].include?(sym)
end
def offense_range(node)
if node.receiver
range_between(node.loc.expression.begin_pos, node.loc.selector.end_pos)
else
node.loc.selector
end
end
end
end
end
end