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.
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 .
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With