Confession: I only use private and public visibility for my methods!
I have a feeling this is a bad thing. But in Rails it just doesn't seem to come up as an issue.
Does anyone have an example in Rails where it would be a big mistake not to use protected visibility?
The second visibility is protected. When calling a protected method the sender must be a subclass of the receiver or the receiver must be a subclass of the sender. Otherwise a NoMethodError will be raised. So the restriction of the visibility is applied to the sender, not the receiver as what you thought.
In Ruby, a protected method (or protected message handler) can only respond to a message with an implicit/explicit receiver (object) of the same family. It also cannot respond to a message sent from outside of the protected message handler context.
You can only use private methods with: This means you can't call private methods from outside the class that defines them.
protected methods can be called by any instance of the defining class or its subclasses. private methods can be called only from within the calling object. You cannot access another instance's private methods directly.
Update -- Please see the comment below that links to a true explanation of protected
/private
in Ruby. That was a deep seated prejudice left over from my Java days, indeed. The only important part left to my answer is that controller methods that are not actions should not be public
(or at least your routes should protect them).
Single Table Inheritance is a perfect example of when protected
is helpful in the model tier, as it's one of the most common uses of inheritance there.
In the controller tier, helper methods defined on ApplicationController
should be marked as protected
-- if they were private
the other controllers would not be able to access them, but if they are public
Rails will treat them as actions.
Personally, I find that I use class inheritance more than many of my friends and coworkers, even in Rails applications. Because I use it often (and coming out of my Java days), I favor protected
for all helper methods to give freedom to anyone (usually myself) who wants to extend the class -- unless I'm really really embarrassed about one, then I mark it private
. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With