Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you ever use protected visibility in Rails?

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?

like image 754
pez_dispenser Avatar asked May 22 '09 06:05

pez_dispenser


People also ask

How do you call a protected method in Ruby?

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.

What does Protected mean in Ruby?

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.

Can you call a private method outside a Ruby class using its object?

You can only use private methods with: This means you can't call private methods from outside the class that defines them.

What is private and protected in Ruby?

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.


1 Answers

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. :)

like image 90
Ian Terrell Avatar answered Oct 24 '22 16:10

Ian Terrell