0

基本クラスでクラス変数を設定する最良の方法は何ですか? CacheMixinActiveRecord モデルで使用される を定義している次のコード スニペットを検討してください。モデルごとに、キャッシュされたデータを格納するテーブルを定義できるようにしたいと考えています。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 に答える