Ruby has this handy and convenient way to share instance variables by using keys like
attr_accessor :var attr_reader :var attr_writer :var
Why would I choose attr_reader
or attr_writer
if I could simply use attr_accessor
? Is there something like performance (which I doubt)? I guess there is a reason, otherwise they wouldn't have made such keys.
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 .
attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs) .
Attributes are specific properties of an object. Methods are capabilities of an object. In Ruby all instance variables (attributes) are private by default. It means you don't have access to them outside the scope of the instance itself. The only way to access the attribute is using an accessor method.
cattr_accessor(*syms, &blk) public. Defines both class and instance accessors for class attributes.
You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.
class Person attr_accessor :age ... end
Here, I can see that I may both read and write the age.
class Person attr_reader :age ... end
Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.
But what is happening behind the scenes?
If you write:
attr_writer :age
That gets translated into:
def age=(value) @age = value end
If you write:
attr_reader :age
That gets translated into:
def age @age end
If you write:
attr_accessor :age
That gets translated into:
def age=(value) @age = value end def age @age end
Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?
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