forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum_uniqueness.rb
85 lines (75 loc) · 2.09 KB
/
enum_uniqueness.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
83
84
85
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Looks for duplicate values in enum declarations.
#
# @example
# # bad
# enum :status, { active: 0, archived: 0 }
#
# # good
# enum :status, { active: 0, archived: 1 }
#
# # bad
# enum :status, [:active, :archived, :active]
#
# # good
# enum :status, [:active, :archived]
#
# # bad
# enum status: { active: 0, archived: 0 }
#
# # good
# enum status: { active: 0, archived: 1 }
#
# # bad
# enum status: [:active, :archived, :active]
#
# # good
# enum status: [:active, :archived]
class EnumUniqueness < Base
include Duplication
MSG = 'Duplicate value `%<value>s` found in `%<enum>s` enum declaration.'
RESTRICT_ON_SEND = %i[enum].freeze
def_node_matcher :enum?, <<~PATTERN
(send nil? :enum $_ ${array hash} ...)
PATTERN
def_node_matcher :enum_with_old_syntax?, <<~PATTERN
(send nil? :enum (hash $...))
PATTERN
def_node_matcher :enum_values, <<~PATTERN
(pair $_ ${array hash})
PATTERN
def on_send(node)
enum?(node) do |key, args|
consecutive_duplicates(args.values).each do |item|
add_offense(item, message: message(key, item))
end
end
enum_with_old_syntax?(node) do |pairs|
pairs.each do |pair|
enum_values(pair) do |key, args|
consecutive_duplicates(args.values).each do |item|
add_offense(item, message: message(key, item))
end
end
end
end
end
private
def enum_name(key)
case key.type
when :sym, :str
key.value
else
key.source
end
end
def message(key, item)
format(MSG, value: item.source, enum: enum_name(key))
end
end
end
end
end