0
在基類中設置類變量的最佳方式是什麼?考慮下面的代碼片段,它定義了要與ActiveRecord模型一起使用的CacheMixin
。對於每個模型,我希望能夠定義存儲緩存數據的表。有沒有更好的方法來做到這一點,而不使用class_variable_set
和class_variable_get
?Ruby mixins - 獲取並設置基類的類變量
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