Is it OK to store every object of certain class in one class array?
Is it OK to create a class array and save every object of that class in it? I'm not sure if there is something similar to this natively in Ruby or a design pattern that accomplish this, so this is my solution for accessing every object of a class:
class Foo
@@all = []
def self.all
@@all
end
def initialize
@@all <&l开发者_StackOverflow中文版t; self
end
end
Foo.all.each do |foo|
# do something
end
You can do it, natively:
ObjectSpace.each_object(Foo) do |foo|
# do something with foo
end
It's problematic in that it will make all instances of the class immortal — the array will keep them alive as long as they are in it. It's better to use ObjectSpace.each_object(Foo)
(mentioned by LBg) or an array of WeakRefs that you periodically cull (this is less space-efficient).
If this is for a short-lived script that won't be using huge data-sets, or you actually want to make all the objects immortal and you'll be careful not to blow the heap, then there is no problem.
You may end up putting too much logic in the Foo
class itself. Instead, you may want to create a FooCollection
object.
This'll prove especially useful if you turn out to need multiple collections of foo
objects. This has happened to me!
精彩评论