An example of Rails controller which defines a private method:
class ApplicationController < ActionController::Base
private
def authorization_method
# do something
end
end
Then, it's being used in a subclass of ApplicationController
:
class CustomerController < ApplicatioController
before_action :authorization_method
# controller actions
end
How is it possible that a private method is called from its subclass? What is the meaning of private
in Ruby?
The only way to have external access to a private method is to call it within a public method. Also, private methods can not be called with an explicit receiver, the receiver is always implicitly self.
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.
Private methods are those methods that should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”.
Both protected and private methods cannot be called from the outside of the defining class. Protected methods are accessible from the subclass and private methods are not. Private methods of the defining class can be invoked by any instance of that class. Public access is the default one.
Private methods cannot be called with an explicit receiver. But they can be called by any subclasses and instances of the class.
Here's a nice explanation of public
, protected
and private
methods in Ruby.
What private
does in Ruby, unlike in other languages, is make so that methods can not be called with explicit receiver.
Aka, you can't call some_variable.some_private_method
or even self.some_private_method
.
That is all. They are still inherited. You can read more here.
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