在基类中设置类变量的最佳方法是什么?考虑以下代码片段,它定义了CacheMixin
用于 ActiveRecord 模型的 a。对于每个模型,我希望能够定义存储缓存数据的表。有没有更好的方法可以在不使用class_variable_set
and的情况下做到这一点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