複数のクラス変数を持つモジュールがあります。クラスが次のようにアクセスしようとしたときにのみ @@ 変数をインスタンス化するクラスレベルのゲッター実装を探しています
module MyProducts
@@products = nil
def self.get_product(id)
# i'm looking for a way that the first call on @@products does a find via AR like the following
# @@products = Product.all
# this module is in the lib directory of a Rails 2.3.5 app
@@products.find do |prod|
prod.id.eql?(id)
end
end
end
モジュール全体を変更する必要がないように、これが透過的であることを探しています。同様の関数を持つ約 10 個のクラス レベル変数があり、すべて ActiveRecord .find 呼び出しの結果です。