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 ...
Matt
source share