Commit a711cbf1 authored by Adam Hegyi's avatar Adam Hegyi

Add static translation check on ivars

parent 53a3e898
...@@ -21,6 +21,8 @@ module RuboCop ...@@ -21,6 +21,8 @@ module RuboCop
method_name = node.children[1] method_name = node.children[1]
return unless TRANSLATION_METHODS.include?(method_name) return unless TRANSLATION_METHODS.include?(method_name)
translation_memoized = false
node.each_ancestor do |ancestor| node.each_ancestor do |ancestor|
receiver, _ = *ancestor receiver, _ = *ancestor
break if lambda_node?(receiver) # translations defined in lambda nodes should be allowed break if lambda_node?(receiver) # translations defined in lambda nodes should be allowed
...@@ -30,6 +32,14 @@ module RuboCop ...@@ -30,6 +32,14 @@ module RuboCop
break break
end end
translation_memoized = true if memoization?(ancestor)
if translation_memoized && class_method_definition?(ancestor)
add_offense(node, location: :expression)
break
end
end end
end end
...@@ -38,6 +48,14 @@ module RuboCop ...@@ -38,6 +48,14 @@ module RuboCop
def constant_assignment?(node) def constant_assignment?(node)
node.type == :casgn node.type == :casgn
end end
def memoization?(node)
node.type == :or_asgn
end
def class_method_definition?(node)
node.type == :defs
end
end end
end end
end end
...@@ -38,6 +38,17 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do ...@@ -38,6 +38,17 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do
['A = _("a")', '_("a")', 1], ['A = _("a")', '_("a")', 1],
['B = s_("b")', 's_("b")', 1], ['B = s_("b")', 's_("b")', 1],
['C = n_("c")', 'n_("c")', 1], ['C = n_("c")', 'n_("c")', 1],
[
<<~CODE,
class MyClass
def self.translations
@cache ||= { hello: _("hello") }
end
end
CODE
'_("hello")',
3
],
[ [
<<~CODE, <<~CODE,
module MyModule module MyModule
...@@ -78,6 +89,20 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do ...@@ -78,6 +89,20 @@ RSpec.describe RuboCop::Cop::StaticTranslationDefinition, type: :rubocop do
'CONSTANT_1 = __("a")', 'CONSTANT_1 = __("a")',
'CONSTANT_2 = s__("a")', 'CONSTANT_2 = s__("a")',
'CONSTANT_3 = n__("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, <<~CODE,
def method def method
s_('a') 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