Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the class constructor private in Ruby?

class A private   def initialize     puts "wtf?"   end end  A.new #still works and calls initialize 

and

class A private   def self.new     super.new   end end 

doesn't work altogether

So what's the correct way? I want to make new private and call it via a factory method.

like image 538
Leonid Shevtsov Avatar asked Oct 14 '09 16:10

Leonid Shevtsov


People also ask

Can we make a class constructor private?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

How do you make a constructor private?

Java allows us to declare a constructor as private. We can declare a constructor private by using the private access specifier. Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we can use this private constructor in Singleton Design Pattern.

How do you make a class private in Ruby?

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.


1 Answers

Try this:

class A   private_class_method :new end 

More on APIDock

like image 73
adurity Avatar answered Sep 19 '22 12:09

adurity