3 ways to make class methods private in Ruby
An overview of the different ways to make class methods private in Ruby
In this article we’re going to explore the following topics:
private_class_method
class << self
andprivate
private_class_method
This method takes one or more method_id
s as an argument. A method_id
can be either a String
or a Symbol
that represents an existing class method in the context of self
. The private_class_method
makes the method correspond to the method_id
passed as argument private
Here we can see that by passing :hello
as argument of private_class_method
the A::hello
class method becomes private
.
Now let’s see another way to make class methods private by also using private_class_method
Here private_class_method
takes the hello
class method definition as an argument. Then we can see that our hello
class method is private
.
To understand what happens here, let’s slightly modify our code
Here we store the return value of the hello
class method definition in method_id
. Then we pass method_id
(which contains :hello
) to private_class_method
. At this moment, the hello
class method becomes private
.
So as a method definition returns the method identifier, we can directly pass the method definition as an argument of private_class_method
.
class << self and private
The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.
Feel free to have a quick look to my article about the eigenclass if you’re not familiar with this concept.
Here, we simply open the eigenclass and make the hello
class method private
.
RubyCademy
Join RubyCademy for more PRO TIPS! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚