This cop checks for redundant uses of `self`.
`self` is only needed when:
Sending a message to same object with zero arguments in presence of a method name clash with an argument or a local variable.
Note, with using explicit self you can only send messages with public or protected scope, you cannot send private messages this way.
Example:
def bar
:baz
end
def foo(bar)
self.bar # resolves name clash with argument
end
def foo2
bar = 1 self.bar # resolves name class with local variable
end
Calling an attribute writer to prevent an local variable assignment
attr_writer :bar
def foo
self.bar= 1 # Make sure above attr writer is called
end
Special cases:
We allow uses of `self` with operators because it would be awkward otherwise.
# File lib/rubocop/cop/style/redundant_self.rb, line 103 def autocorrect(node) receiver, _method_name, *_args = *node @corrections << lambda do |corrector| corrector.remove(receiver.loc.expression) corrector.remove(node.loc.dot) end end
# File lib/rubocop/cop/style/redundant_self.rb, line 77 def on_args(node) node.children.each { |arg| on_argument(arg) } end
# File lib/rubocop/cop/style/redundant_self.rb, line 81 def on_blockarg(node) on_argument(node) end
Using self.x to distinguish from local variable x
# File lib/rubocop/cop/style/redundant_self.rb, line 69 def on_def(_node) @local_variables = [] end
# File lib/rubocop/cop/style/redundant_self.rb, line 73 def on_defs(_node) @local_variables = [] end
# File lib/rubocop/cop/style/redundant_self.rb, line 85 def on_lvasgn(node) lhs, _rhs = *node @local_variables << lhs end
# File lib/rubocop/cop/style/redundant_self.rb, line 62 def on_op_asgn(node) lhs, _op, _rhs = *node allow_self(lhs) end
Assignment of self.x
# File lib/rubocop/cop/style/redundant_self.rb, line 55 def on_or_asgn(node) lhs, _rhs = *node allow_self(lhs) end
Detect offenses
# File lib/rubocop/cop/style/redundant_self.rb, line 92 def on_send(node) receiver, method_name, *_args = *node return unless receiver && receiver.type == :self return if operator?(method_name) || keyword?(method_name) || constant_name?(method_name) || @allowed_send_nodes.include?(node) || @local_variables.include?(method_name) add_offense(node, :expression) end
Generated with the Darkfish Rdoc Generator 2.