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