在Ruby中为静态实例初始值设定项(即工厂方法)初始化

在Ruby中为静态实例初始值设定项(即工厂方法)初始化,ruby,static,initialization,Ruby,Static,Initialization,我有一个类,我想把工厂方法放在上面,根据两种构造方法中的一种生成一个新实例:它可以从内存中的数据构造,也可以从文件中存储的数据构造 我想做的是封装类内如何执行构造的逻辑,因此我希望有如下设置的静态类方法: class MyAppModel def initialize #Absolutely nothing here - instances are not constructed externally with MyAppModel.new end de

我有一个类,我想把工厂方法放在上面,根据两种构造方法中的一种生成一个新实例:它可以从内存中的数据构造,也可以从文件中存储的数据构造

我想做的是封装类内如何执行构造的逻辑,因此我希望有如下设置的静态类方法:

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

如果不借助元编程(instance_variable_set),就无法从类本身在类的实例上设置@some_private_var吗?这种模式似乎并不深奥到需要将变量插入实例的程度。我真的不想让MyAppModel之外的任何类访问某些已发布的变量,所以我不想使用例如attr\u accessor-这感觉好像我遗漏了什么…

也许使用构造函数是实现您想要的更好的方法,如果您不想从“外部”创建实例,请保护它

类MyAppModel

类这是非常好的和惯用的。谢谢,我认为这比我所做的要干净得多-它仍然需要向构造函数传递一些东西,但是因为它无论如何都是受保护的,这没什么大不了的-而且比实例变量集好得多。
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