How to make the class constructor private in Ruby?

前端 未结 3 1913
北荒
北荒 2020-12-08 06:10
class A
private
  def initialize
    puts \"wtf?\"
  end
end

A.new #still works and calls initialize

and

class A
private
  def sel         


        
3条回答
  •  星月不相逢
    2020-12-08 06:57

    To shed some light on the usage, here is a common example of the 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
         # e.g. 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 as

    result = A.create('some argument')    
    

    As expected, the runtime error occurs in the case of direct new usage:

    a = A.new('this leads to the error')
    

提交回复
热议问题