How to make the class constructor private in Ruby?

前端 未结 3 1911
北荒
北荒 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:54

    The second chunk of code you tried is almost right. The problem is private is operating in the context of instance methods instead of class methods.

    To get private or private :new to work, 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 truly want to redefine new and call super

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

    Class-level factory methods can access the private new just fine, but trying to instantiate directly using new will fail because new is private.

提交回复
热议问题