Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually occurs when stating "private"/"protected" in Ruby?

What is actually occurring when private/protected is stated within a Ruby class definition? They are not keywords, so that implies they must be method calls, but I cannot find where they are defined. They do not appear to be documented. Are the two different ways of declaring private/protected methods (shown below) implemented differently? (The second way is obviously a method call, but this is not so apparent in the first way.)

class Foo
  private
  def i_am_private; end
  def so_am_i; end
end

class Foo
  def i_am_private; end
  def so_am_i; end
  private :i_am_private, :so_am_i
end
like image 818
Andrew Marshall Avatar asked Nov 05 '11 20:11

Andrew Marshall


People also ask

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.

How does private work in Ruby?

What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.

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.

How do you access protected methods in Ruby?

Protected methods can only be called by objects of the defined class and its subclass. The access of these methods is limited in between the defined class or its subclass. You cannot access protected methods outside the defined class or its subclass. The usage of protected methods is finite.


1 Answers

Both are method calls. Quoting from docs:

Each function can be used in two different ways.

  1. If used with no arguments, the three functions set the default access control of subsequently defined methods.
  2. With arguments, the functions set the access control of the named methods and constants.

See documentation here:

  1. Module.private
  2. Access Control

You were looking for how the Module.private method comes into existence. Here is where that happens. And here is some more information about it. You would have to read more into it, starting from rb_define_private_method defined in class.c.

Hope that helps!

like image 72
Zabba Avatar answered Oct 17 '22 00:10

Zabba