【发布时间】:2011-11-23 05:54:03
【问题描述】:
我有一个包含多个类变量的模块。我正在寻找一个类级别的 getter 实现,它只会在类尝试访问它时实例化 @@ 变量,如下所示
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 调用的结果
【问题讨论】:
标签: ruby-on-rails ruby class-variables