How to make 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 

not working at all

So what is the right way? I want to make new private and call it using the factory method.

+43
constructor ruby access-specifier
Oct 14 '09 at 16:18
source share
3 answers

Try the following:

 class A private_class_method :new end 

Learn more about APIDock.

+65
Oct. 14 '09 at 16:33
source share

The second piece of code you tried is almost right. The problem is that private works in the context of instance methods instead of class methods.

To work private or private :new , you just need to force it to be in the context of class methods like this:

 class A class << self private :new end end 

Or if you really want to override new and call super

 class A class << self private def new(*args) super(*args) # additional code here end end end 

The methods of the factory class class can access the closed new simply, but trying to instantiate directly with new will fail because new is private.

+13
Sep 30 '15 at 18:50
source share

To shed light on usage, here is a general example of a factory method:

 class A def initialize(argument) # some initialize logic end # mark A.new constructor as private private_class_method :new # add a class level method that can return another type # (not exactly, but close to `static` keyword in other languages) def self.create(my_argument) # some logic # eg return an error object for invalid arguments return Result.error('bad argument') if(bad?(my_argument)) # create new instance by calling private :new method instance = new(my_argument) Result.new(instance) end end 

Then use it like

 result = A.create('some argument') 

As expected, a runtime error occurs when directly using new :

 a = A.new('this leads to the error') 
0
Sep 14 '17 at 16:00
source share



All Articles