I would like one instance of a model in memory to serve as a template for creating other objects for performance reasons, so that duplicates look like the original object but otherwise share no common components with the object they are initialized from, as if they were loaded with Model.find(template_object.id). I've tried some of the available solutions but none seems to do what I need: .dup and .deep_dup will create a new object with nil id and .clone will make some of the fields common to both the initializer and the initialized.
Currently my API is giving out the original objects that I keep as class variables, but I discovered that it leads to obscure memory leaks when the code using the objects manipulates their associations - these are kept in memory indefinitely. I hope that by giving out copies the associations of the template objects will stay untouched and the leak will be gone.
CodePudding user response:
This sounds like the use case for defining a class and just initializing instances. You can customize whatever properties you want shared in the MyClass#new
method. Without knowing more about your needs I will add that if you must store a template in memory you could store it as a class variable perhaps MyClass@@template
but would need to hear more to opine further.