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

왜 예방할 수 있습니까? 당신은'class B

+0

'history_tables'가 클래스 변수이고 B에서'history_tables'의 값을 변경하면'B