forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pluralization_grammar.rb
107 lines (85 loc) · 2.83 KB
/
pluralization_grammar.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop checks for correct grammar when using ActiveSupport's
# core extensions to the numeric classes.
#
# @example
# # bad
# 3.day.ago
# 1.months.ago
#
# # good
# 3.days.ago
# 1.month.ago
class PluralizationGrammar < Cop
SINGULAR_DURATION_METHODS = { second: :seconds,
minute: :minutes,
hour: :hours,
day: :days,
week: :weeks,
fortnight: :fortnights,
month: :months,
year: :years }.freeze
PLURAL_DURATION_METHODS = SINGULAR_DURATION_METHODS.invert.freeze
MSG = 'Prefer `%<number>s.%<correct>s`.'
def on_send(node)
return unless duration_method?(node.method_name)
return unless literal_number?(node.receiver)
return unless offense?(node)
add_offense(node)
end
def autocorrect(node)
lambda do |corrector|
method_name = node.loc.selector.source
corrector.replace(node.loc.selector, correct_method(method_name))
end
end
private
def message(node)
number, = *node.receiver
format(MSG, number: number,
correct: correct_method(node.method_name.to_s))
end
def correct_method(method_name)
if plural_method?(method_name)
singularize(method_name)
else
pluralize(method_name)
end
end
def offense?(node)
number, = *node.receiver
singular_receiver?(number) && plural_method?(node.method_name) ||
plural_receiver?(number) && singular_method?(node.method_name)
end
def plural_method?(method_name)
method_name.to_s.end_with?('s')
end
def singular_method?(method_name)
!plural_method?(method_name)
end
def singular_receiver?(number)
number.abs == 1
end
def plural_receiver?(number)
!singular_receiver?(number)
end
def literal_number?(node)
node && (node.int_type? || node.float_type?)
end
def pluralize(method_name)
SINGULAR_DURATION_METHODS.fetch(method_name.to_sym).to_s
end
def singularize(method_name)
PLURAL_DURATION_METHODS.fetch(method_name.to_sym).to_s
end
def duration_method?(method_name)
SINGULAR_DURATION_METHODS.key?(method_name) ||
PLURAL_DURATION_METHODS.key?(method_name)
end
end
end
end
end