Commit ba920779 authored by Peter Leitzen's avatar Peter Leitzen

Merge branch '214635-static-translation-definitions-v2' into 'master'

Add static translation check on ivars

Closes #214635

See merge request gitlab-org/gitlab!41878
parents a5698e3f a711cbf1
......@@ -21,6 +21,8 @@ module RuboCop
method_name = node.children[1]
return unless TRANSLATION_METHODS.include?(method_name)
translation_memoized = false
node.each_ancestor do |ancestor|
receiver, _ = *ancestor
break if lambda_node?(receiver) # translations defined in lambda nodes should be allowed
......@@ -30,6 +32,14 @@ module RuboCop
break
end
translation_memoized = true if memoization?(ancestor)
if translation_memoized && class_method_definition?(ancestor)
add_offense(node, location: :expression)
break
end
end
end
......@@ -38,6 +48,14 @@ module RuboCop
def constant_assignment?(node)
node.type == :casgn
end
def memoization?(node)
node.type == :or_asgn
end
def class_method_definition?(node)
node.type == :defs
end
end
end
end
......@@ -38,6 +38,17 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do
['A = _("a")', '_("a")', 1],
['B = s_("b")', 's_("b")', 1],
['C = n_("c")', 'n_("c")', 1],
[
<<~CODE,
class MyClass
def self.translations
@cache ||= { hello: _("hello") }
end
end
CODE
'_("hello")',
3
],
[
<<~CODE,
module MyModule
......@@ -78,6 +89,20 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do
'CONSTANT_1 = __("a")',
'CONSTANT_2 = s__("a")',
'CONSTANT_3 = n__("a")',
<<~CODE,
class MyClass
def self.method
@cache ||= { hello: -> { _("hello") } }
end
end
CODE
<<~CODE,
class MyClass
def method
@cache ||= { hello: _("hello") }
end
end
CODE
<<~CODE,
def method
s_('a')
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment