【发布时间】:2013-04-18 12:22:42
【问题描述】:
在基类中设置类变量的最佳方法是什么?考虑下面的代码 sn-p,它定义了一个 CacheMixin 用于 ActiveRecord 模型。对于每个模型,我希望能够定义存储缓存数据的表。不使用class_variable_set 和class_variable_get 有没有更好的方法?
require 'rubygems'
require 'active_support/concern'
module CacheMixin
extend ActiveSupport::Concern
module ClassMethods
def with_cache_table(table)
self.class_variable_set('@@cache_table', table)
end
end
def fetch_data
puts self.class.class_variable_get('@@cache_table')
end
end
class TestClass
include CacheMixin
with_cache_table("my_cache_table")
end
【问题讨论】: