1

我需要一个不会继承的类变量,所以我决定使用一个类实例变量。目前我有这样的代码:如何在Ruby中声明一个类实例变量?

class A 
    def self.symbols 
    history_symbols 
    end 

    private 

    def self.history_tables 
    @@history_tables ||= ActiveRecord::Base.connection.tables.select do |x| 
     x.starts_with?(SOME_PREFIX) 
    end 
    end 

    def self.history_symbols 
    Rails.cache.fetch('history_symbols', expires_in: 10.minutes) do 
     history_tables.map { |x| x.sub(SOME_PREFIX, '') } 
    end 
    end 
end 

我可以安全地将@@ history_tables转换为@history_tables而不用制动任何东西吗?目前我所有的测试都通过了,但我仍然不确定是否可以这样做。

回答

1

既然你想使用的实例变量,你必须使用实例之类的,而不是单方法:

class A 
    def symbols 
    history_symbols  
    end 

    private 

    def history_tables 
    @history_tables ||= ActiveRecord::Base.connection.tables.select do |x| 
     x.starts_with?(SOME_PREFIX) 
    end 
    end 

    def history_symbols 
    Rails.cache.fetch('history_symbols', expires_in: 10.minutes) do 
     history_tables.map { |x| x.sub(SOME_PREFIX, '') } 
    end 
    end 
end 

A.new.symbols 

代替:

A.symbols 
+0

是的,没错,那是什么我很担心。我如何继续使用这个类,但仍然阻止继承? –

+0

为什么会阻止?你可以做'B级

+0

如果'history_tables'是一个类变量,并且如果我在B中更改'history_tables'的值,那么我有'B