Ruby – Access Control

It is important to consider how much of your class you’ll be exposing to the outside world. Ruby give you three levels of protection.

Public methods – can be called by anyone. Methods are public by default. Initialize method is always private.

Protected methods – can be invoked by objects of the defining class and its subclasses.

Private methods – can be called only in the context of the current object; can’t invoke another object’s private methods.

You will get access violation only when the code attempts to execute the restricted method.

You specify access levels to methods within class or module definitions using public, protected and private.

<br /><br />#without arguments<br /><br />class MyClass<br /><br />def method1   #default is 'public'<br /><br />#...<br /><br />end<br /><br />protected    #subsequent methods will be 'protected'<br /><br />def method2<br /><br />#...<br /><br />end<br /><br />private   #subsequent methods will be 'private'<br /><br />def method3<br /><br />#...<br /><br />end<br /><br />public   #subsequent methods will be 'public'<br /><br />def method4<br /><br />#...<br /><br />end<br /><br />end<br /><br />#with arguments<br /><br />class MyClass<br /><br />def method1<br /><br />end<br /><br />def method2<br /><br />end<br /><br /># ... and so on<br /><br />public :method1, :method4<br /><br />protected :method2<br /><br />private :method4<br /><br />end<br /><br />

Something to take note of.

In Ruby, public, private and protected apply only to methods. Instance and class variables are encapsulated and effectively private, and constants are effectively public. There is no way to make an instance variable accessible from outside a class (except by defining an accessor method). And there is no way to define a constant that is inaccessible to outside use.

Classes often use private methods as internal helper methods. They are not part of the public API of the class and are not intended to be visible. If you happen to define a method in your subclass that has the same name as a private method in the superclass, you will have inadvertently overridden the superclass’s internal utility method, and this will almost certainly cause unintended behavior.