Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Private vs. Protected? [duplicate]

Question, can you have private and protected in a single Ruby on Rails controller? If not, which one is preferred in a devise controller, or a regular controller for a model?

Thanks

like image 698
Corey Avatar asked Feb 10 '17 16:02

Corey


People also ask

What does private do in Rails?

If a method is private, it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).

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.

What's the difference between a protected method and a private method?

The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class. Private member are not inherited in class.

What is protected vs private?

private: The type or member can be accessed only by code in the same class or struct . protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class .


1 Answers

can you have private and protected in a single Ruby on Rails controller?

Yes, you can. Rails controllers are just classes, and classes can have any number and combination of private and protected blocks.

Use protected if you want to allow for inherited controllers to access the method. Use private if you want the method to be accessible only by the controller itself.

like image 119
meagar Avatar answered Oct 04 '22 07:10

meagar