Class: RuboCop::Cop::Rails::FindByOrAssignmentMemoization
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Rails::FindByOrAssignmentMemoization
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/rails/find_by_or_assignment_memoization.rb
Overview
Avoid memoizing ‘find_by` results with `||=`.
It is common to see code that attempts to memoize ‘find_by` result by `||=`, but `find_by` may return `nil`, in which case it is not memoized as intended.
NOTE: Respecting the object shapes introduced in Ruby 3.2, instance variables used for memoization that are initialized at object creation are ignored.
Constant Summary collapse
- MSG =
'Avoid memoizing `find_by` results with `||=`.'- RESTRICT_ON_SEND =
i[find_by].freeze
Instance Method Summary collapse
-
#on_def(node) ⇒ Object
When a method body contains only memoization, the correction can be more succinct.
- #on_send(node) ⇒ Object
Instance Method Details
#on_def(node) ⇒ Object
When a method body contains only memoization, the correction can be more succinct.
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/rubocop/cop/rails/find_by_or_assignment_memoization.rb', line 61 def on_def(node) find_by_or_assignment_memoization(node.body) do |variable_name, find_by| next if instance_variable_assigned?(variable_name) add_offense(node.body) do |corrector| corrector.replace( node.body, " return \#{variable_name} if defined?(\#{variable_name})\n\n \#{variable_name} = \#{find_by.source}\n RUBY\n )\n\n correct_to_regular_method_definition(corrector, node) if node.endless?\n end\n end\nend\n".rstrip |
#on_send(node) ⇒ Object
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/rubocop/cop/rails/find_by_or_assignment_memoization.rb', line 80 def on_send(node) assignment_node = node.parent find_by_or_assignment_memoization(assignment_node) do |variable_name, find_by| next if assignment_node.each_ancestor(:if).any? || instance_variable_assigned?(variable_name) add_offense(assignment_node) do |corrector| corrector.replace( assignment_node, " if defined?(\#{variable_name})\n \#{variable_name}\n else\n \#{variable_name} = \#{find_by.source}\n end\n RUBY\n )\n end\n end\nend\n".rstrip |