0

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

1 回答 1

0

由于您使用的是 Rails,我建议您查看该class_attribute方法。

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

class Foo
  class << self
    attr_accessor :bar
  end
end

Foo.bar = 'hi'
p Foo.bar
#=> 'hi'
于 2013-04-18T12:45:45.900 回答