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