Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private methods in Ruby

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?

like image 493
rails8 Avatar asked Sep 11 '15 13:09

rails8


People also ask

How do you access a private method 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.

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 are private methods?

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 “__”.

What is the difference between private and protected methods in Ruby?

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.


2 Answers

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.

like image 159
Daniel Avatar answered Oct 02 '22 12:10

Daniel


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.

like image 25
ndnenkov Avatar answered Oct 02 '22 11:10

ndnenkov