Ruby中的类静态实例初始值设定项(即工厂方法)

Mat*_*att 7 ruby static initialization

我有一个类,我希望将工厂方法放在基于两种构造方法之一的新实例上:它可以从内存中的数据构建,也可以由存储在文件中的数据构建.

我想要做的是封装在类中执行构造的逻辑,所以我希望有这样设置的静态类方法:

class MyAppModel
    def initialize
        #Absolutely nothing here - instances are not constructed externally with MyAppModel.new
    end

    def self.construct_from_some_other_object otherObject
        inst = MyAppModel.new
        inst.instance_variable_set("@some_non_published_var", otherObject.foo)
        return inst
    end

    def self.construct_from_file file
        inst = MyAppModel.new
        inst.instance_variable_set("@some_non_published_var", get_it_from_file(file))
        return inst
    end
end
Run Code Online (Sandbox Code Playgroud)

有没有办法在类的实例上设置@some_private_var而不依赖于元编程(instance_variable_set)?看起来这种模式并不是那么深奥,以至于需要将meta-poking变量放入实例中.我真的不打算允许MyAppModel之外的任何类访问some_published_var,所以我不想使用例如attr_accessor - 它只是感觉我错过了一些东西......

Hol*_*lin 9

也许使用构造函数是获得所需内容的更好方法,如果您不想从"外部"创建实例,则可以使其受到保护

class MyAppModel
  class << self
    # ensure that your constructor can't be called from the outside
    protected :new

    def construct_from_some_other_object(other_object)
      new(other_object.foo)
    end

    def construct_from_file(file)
      new(get_it_from_file(file))
    end
  end

  def initialize(my_var)
    @my_var = my_var
  end
end
Run Code Online (Sandbox Code Playgroud)