I’m trying to get a good Ruby coding style. To prevent accidently calling a local variable with the same name, I’m always using self. where appropriate. But now I stumbled over this:
class MyClass < ActiveRecord::Base
before_validation :sanitize_user_data
private
def sanitize_user_data
self.sanitize_name # with ".self" it's a problem, without it's not!
end
def sanitize_name
unless self.name.nil?
self.name.gsub!(/\s+/, ' ')
self.name.strip!
end
end
end
The above code results in an error
private method
sanitize_namecalled
but when removing self. and just using sanitize_name, it works. Why’s that?
This happens because private methods cannot be called with an explicit receiver, and saying
self.sanitize_nameis explicitly specifying the object (self) that should receivesanitize_name, rather than relying on the implicit receiver (which is alsoself).You can’t avoid this, you either need to call plain old
sanitize_namewithout an explicit receiver, or doself.send(:sanitize_name). I’m not sure that always explicitly specifyingselfis really “good style”, but that’s subjective. If you want to ensure you’re calling a method instead of a variable, add parenthesis: