Initializers of static class instances (i.e. factory methods) in Ruby

I have a class in which I want to put factory methods to spit out a new instance based on one of two construction methods: either it can be built from data in memory, or data stored in a file.

What I would like to do is encapsulate the logic of how the construct is executed inside the class, so I would like to have static class methods that are configured as follows:

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 

Is there no way to set @some_private_var in an instance of a class from the class itself without resorting to metaprogramming (instance_variable_set)? It seems that this template is not so esoteric as to require metapot variables in instances. I really do not intend to allow any class outside MyAppModel access to some_published_var, so I do not want to use, for example. attr_accessor - it just feels like I'm missing something ...

+7
source share
1 answer

Perhaps using a constructor is the best way to achieve what you want, just make it secure if you don't want to instantiate from "external"

 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 
+9
source

All Articles