Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cattr_accessor in Rails?

Im reading the Rails guides for Rails 3 and they use this method:

cattr_accessor :attribute 

What is this method? Is it a Rails method? I've never seen it before.

like image 330
never_had_a_name Avatar asked Aug 05 '10 02:08

never_had_a_name


People also ask

What is Attr_accessor in Ruby?

Nouman Abbasi. In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .

How do you define a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

What is class attribute in Ruby?

class_attribute(*attrs) public. Declare a class-level attribute whose value is inheritable by subclasses. Subclasses can change their own value and it will not impact parent class.


1 Answers

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"  
like image 175
Matt Briggs Avatar answered Oct 02 '22 07:10

Matt Briggs