【问题标题】:Ruby mixins -- getting & setting base class' class variablesRuby mixins——获取和设置基类的类变量
【发布时间】:2013-04-18 12:22:42
【问题描述】:

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

【问题讨论】:

    标签: ruby mixins


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多