本文介绍了Rails 中的 cattr_accessor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读 Rails 3 的 Rails 指南,他们使用这种方法:
Im reading the Rails guides for Rails 3 and they use this method:
cattr_accessor :attribute
这是什么方法?它是一个 Rails 方法吗?我以前从未见过.
What is this method? Is it a Rails method? I've never seen it before.
推荐答案
这是一个 Rails 的事情.基本上像 attr_* 方法,但用于类级别.您不会想到的一件事是因为它使用了一个支持 @@ 变量,该变量在类和所有实例之间共享.
It is a rails thing. Basically like the attr_* methods, but for the class level. One thing you wouldn't expect is because it uses a backing @@ variable, the value shared between the class and all instances.
class Foo
cattr_accessor :bar
end
# => [:bar]
foo1 = Foo.new
# => #<Foo:0x4874d90>
foo2 = Foo.new
# => #<Foo:0x4871d48>
foo1.bar = 'set from instance'
# => "set from instance"
foo2.bar
# => "set from instance"
Foo.bar
# => "set from instance"
这篇关于Rails 中的 cattr_accessor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!