次のようなものが必要ですが、異なるクラスで再利用できるようにしたいと考えています。
このコードをリファクタリングして、最小限の労力でクラスに含めることができ、そのクラスは new が呼び出されるたびに自動的にインスタンスを収集するようにするにはどうすればよいですか?
new や initialize をオーバーライドするなど、あらゆる種類のことを試しましたが、魔法を起こすことはできません。
   class Person      
      @@people_instances = []
      def initialize
         @@people_instances << self
      end
      def self.instances
         @@people_instances
      end
   end
People.new
People.new
Poople.instances
 => [#<Person:0x000001071a7e28>, #<Person:0x000001071a3828>] 
以下のいくつかのフィードバックの後、答えはインスタンスをクラス変数に入れることではないと思います。インスタンスは永久にメモリに残るからです。インスタンスを保持する必要がないため、Rails キャッシュも適切ではありません。
次のコードでは、クラス変数の代わりにクラス インスタンス変数を使用しています。
http://www.dzone.com/snippets/class-variables-vs-class
class Employee
  class << self; attr_accessor :instances; end
  def store
    self.class.instances ||= []
    self.class.instances << self
  end
  def initialize name
    @name = name
  end
end
class Overhead < Employee; end
class Programmer < Employee; end
Overhead.new('Martin').store
Overhead.new('Roy').store
Programmer.new('Erik').store
puts Overhead.instances.size    # => 2
puts Programmer.instances.size  # => 1
これらのインスタンス変数は、すべての Rails リクエストに固有のものですか、それとも存続しますか?