forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment_comparison.rb
68 lines (59 loc) · 1.72 KB
/
environment_comparison.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop checks that Rails.env is compared using `.production?`-like
# methods instead of equality against a string or symbol.
#
# @example
# # bad
# Rails.env == 'production'
#
# # bad, always returns false
# Rails.env == :test
#
# # good
# Rails.env.production?
class EnvironmentComparison < Cop
MSG = "Favor `Rails.env.%<env>s?` over `Rails.env == '%<env>s'`."
SYM_MSG = 'Do not compare `Rails.env` with a symbol, it will always ' \
'evaluate to `false`.'
def_node_matcher :environment_str_comparison?, <<~PATTERN
(send
(send (const {nil? cbase} :Rails) :env)
:==
$str
)
PATTERN
def_node_matcher :environment_sym_comparison?, <<~PATTERN
(send
(send (const {nil? cbase} :Rails) :env)
:==
$sym
)
PATTERN
def on_send(node)
environment_str_comparison?(node) do |env_node|
env, = *env_node
add_offense(node, message: format(MSG, env: env))
end
environment_sym_comparison?(node) do |_|
add_offense(node, message: SYM_MSG)
end
end
def autocorrect(node)
lambda do |corrector|
corrector.replace(node.source_range, replacement(node))
end
end
private
def replacement(node)
"#{node.receiver.source}.#{content(node.first_argument)}?"
end
def_node_matcher :content, <<~PATTERN
({str sym} $_)
PATTERN
end
end
end
end