How to declare a class instance variable in Ruby?

199 Views Asked by At

I need a class variable which does not get inherited, so I decided to use a class instance variable. Currently I have this code:

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

Can I safely transform @@history_tables to @history_tables without braking anything? Currently all my tests pass, but I am still not sure if this could be done just like that.

1

There are 1 best solutions below

4
On

Since you wish to use the instance variable, you shall use instance of the class, instead of the singleton methods:

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

instead of:

A.symbols