forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshort_i18n.rb
74 lines (66 loc) · 2.03 KB
/
short_i18n.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop enforces that short forms of `I18n` methods are used:
# `t` instead of `translate` and `l` instead of `localize`.
#
# This cop has two different enforcement modes. When the EnforcedStyle
# is conservative (the default) then only `I18n.translate` and `I18n.localize`
# calls are added as offenses.
#
# When the EnforcedStyle is aggressive then all `translate` and `localize` calls
# without a receiver are added as offenses.
#
# @example
# # bad
# I18n.translate :key
# I18n.localize Time.now
#
# # good
# I18n.t :key
# I18n.l Time.now
#
# @example EnforcedStyle: conservative (default)
# # good
# translate :key
# localize Time.now
# t :key
# l Time.now
#
# @example EnforcedStyle: aggressive
# # bad
# translate :key
# localize Time.now
#
# # good
# t :key
# l Time.now
#
class ShortI18n < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Use `%<good_method>s` instead of `%<bad_method>s`.'
PREFERRED_METHODS = {
translate: :t,
localize: :l
}.freeze
RESTRICT_ON_SEND = PREFERRED_METHODS.keys.freeze
def_node_matcher :long_i18n?, <<~PATTERN
(send {nil? (const nil? :I18n)} ${:translate :localize} ...)
PATTERN
def on_send(node)
return if style == :conservative && !node.receiver
long_i18n?(node) do |method_name|
good_method = PREFERRED_METHODS[method_name]
message = format(MSG, good_method: good_method, bad_method: method_name)
range = node.loc.selector
add_offense(range, message: message) do |corrector|
corrector.replace(range, PREFERRED_METHODS[method_name])
end
end
end
end
end
end
end