Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在Ruby中声明类实例变量?_Ruby On Rails_Ruby_Refactoring_Class Variables_Class Instance Variables - Fatal编程技术网

Ruby on rails 如何在Ruby中声明类实例变量?

Ruby on rails 如何在Ruby中声明类实例变量?,ruby-on-rails,ruby,refactoring,class-variables,class-instance-variables,Ruby On Rails,Ruby,Refactoring,Class Variables,Class Instance Variables,我需要一个不会被继承的类变量,所以我决定使用一个类实例变量。目前我有以下代码: 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

我需要一个不会被继承的类变量,所以我决定使用一个类实例变量。目前我有以下代码:

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\u表转换为@history\u表,而不必停止任何操作吗?目前,我的所有测试都通过了,但我仍然不确定是否可以这样做。

因为您希望使用实例变量,所以应该使用类的实例,而不是单例方法:

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

是的,没错,这正是我担心的。如何继续使用该类但仍然阻止继承?为什么阻止继承?你可以做
B类
如果
history\u tables
是一个类变量,我有
B
如果我在B中更改
history\u tables
的值,它也会在a中更改。我不希望这样。@AlexPopov不,因为你必须创建一个新实例,所以不能用另一个实例替换它
A.新建
您不能更改为
B
。但是
B.new
您仍然可以使用一个新的实例变量
history\u tables
执行
B.new.symbols