class RuboCop::Cop::Lint::UselessSetterCall
Checks for setter call to local variable as the final expression of a function definition.
@safety
There are edge cases in which the local variable references a value that is also accessible outside the local scope. This is not detected by the cop, and it can yield a false positive. As well, autocorrection is unsafe because the method's return value will be changed.
@example
# bad def something x = Something.new x.attr = 5 end
@example
# good def something x = Something.new x.attr = 5 x end
Constants
- ASSIGNMENT_TYPES
- MSG
Public Instance Methods
on_def(node)
click to toggle source
# File lib/rubocop/cop/lint/useless_setter_call.rb, line 41 def on_def(node) return unless node.body last_expr = last_expression(node.body) return unless setter_call_to_local_variable?(last_expr) tracker = MethodVariableTracker.new(node.body) receiver, = *last_expr variable_name, = *receiver return unless tracker.contain_local_object?(variable_name) loc_name = receiver.loc.name add_offense(loc_name, message: format(MSG, variable: loc_name.source)) do |corrector| corrector.insert_after(last_expr, "\n#{indent(last_expr)}#{loc_name.source}") end end
Also aliased as: on_defs
Private Instance Methods
last_expression(body)
click to toggle source
# File lib/rubocop/cop/lint/useless_setter_call.rb, line 67 def last_expression(body) expression = body.begin_type? ? body.children : body expression.is_a?(Array) ? expression.last : expression end