2013-04-18 29 views
0

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

回答

0

由於您使用Rails,我建議您檢查一下class_attribute方法。

如果你想在沒有Rails的情況下這樣做,我建議直接在類對象上設置一個實例變量,而不是使用類變量(這通常被認爲是壞消息)。

class Foo 
    class << self 
    attr_accessor :bar 
    end 
end 

Foo.bar = 'hi' 
p Foo.bar 
#=> 'hi'