Ruby mixins -- 获取和设置基类的类变量



在基类中设置类变量的最佳方法是什么?考虑下面的代码片段,它定义了一个与ActiveRecord模型一起使用的CacheMixin。对于每个模型,我都希望能够定义存储缓存数据的表。在不使用class_variable_setclass_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

既然您正在使用Rails,我建议您检查class_attribute方法。

如果你想在没有Rails的情况下这样做,我建议直接在类对象上设置实例变量,而不是使用类变量(这通常被认为是坏消息)。

class Foo
  class << self
    attr_accessor :bar
  end
end
Foo.bar = 'hi'
p Foo.bar
#=> 'hi'

最新更新