forked from rubocop/rubocop
/
hash_as_last_array_item.rb
78 lines (67 loc) · 1.88 KB
/
hash_as_last_array_item.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for presence or absence of braces around hash literal as a last
# array item depending on configuration.
#
# NOTE: This cop will ignore arrays where all items are hashes, regardless of
# EnforcedStyle.
#
# @example EnforcedStyle: braces (default)
# # bad
# [1, 2, one: 1, two: 2]
#
# # good
# [1, 2, { one: 1, two: 2 }]
#
# # good
# [{ one: 1 }, { two: 2 }]
#
# @example EnforcedStyle: no_braces
# # bad
# [1, 2, { one: 1, two: 2 }]
#
# # good
# [1, 2, one: 1, two: 2]
#
# # good
# [{ one: 1 }, { two: 2 }]
class HashAsLastArrayItem < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
def on_hash(node)
return unless last_array_item?(node)
if braces_style?
check_braces(node)
else
check_no_braces(node)
end
end
private
def last_array_item?(node)
parent = node.parent
return false unless parent&.array_type?
return false if parent.child_nodes.all?(&:hash_type?)
parent.children.last.equal?(node)
end
def check_braces(node)
return if node.braces?
add_offense(node, message: 'Wrap hash in `{` and `}`.') do |corrector|
corrector.wrap(node, '{', '}')
end
end
def check_no_braces(node)
return unless node.braces?
add_offense(node, message: 'Omit the braces around the hash.') do |corrector|
corrector.remove(node.loc.begin)
corrector.remove(node.loc.end)
end
end
def braces_style?
style == :braces
end
end
end
end
end