Class static instance initializers (i.e. factory methods) in Ruby -


i have class want put factory methods on spit out new instance based on 1 of 2 construction methods: either can constructed data in memory, or data stored in file.

what encapsulate logic of how construction performed inside class, have static class methods set this:

class myappmodel     def initialize         #absolutely nothing here - instances not constructed externally 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 set @some_private_var on instance of class class without resorting metaprogramming (instance_variable_set)? seems pattern not esoteric require meta-poking variables instances. don't intend allow class outside of myappmodel have access some_published_var, don't want use e.g. attr_accessor - feels i'm missing something...

maybe using constructor better way achieve want, make protected if don't want create instances "outside"

class myappmodel   class << self     # ensure constructor can't called 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 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -