newbie alert
I'm watching one of Ryan Bate's RailsCasts on virtual attributes. He's adding tags to an article on a blogging platform. http://media.railscasts.com/assets/episodes/videos/167-more-on-virtual-attributes.mp4
At one point he has working code
attr_accessor :tag_names
In this example, the tag names do not appear in the form if they validate, so he changes the name of the attribute, and adds a method so that the tag names persist if there's a validation error on a different field
attr_writer :tag_names
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
My question is, can you please explain the significance of changing it from attr_accessor
to attr_writer
in combination with the method he added? Why did he need to change the attribute name when he added that method?
(note, i have read documentation about attr_accessor and attr_writer, but it's still not clicking enough so I'm not getting why he's making this change when he creates that method)
attr_accessorattr_accessorIn computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (together also known as accessors), which returns the value of the private member variable.https://en.wikipedia.org › wiki › Mutator_methodMutator method - Wikipedia is used to define an attribute for object of Model which is not mapped with any column in database.
attr_accessorattr_accessorIn computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (together also known as accessors), which returns the value of the private member variable.https://en.wikipedia.org › wiki › Mutator_methodMutator method - Wikipedia is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.
Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.
Attributes are key-value pairs containing information that determines the properties of an event or transaction. These key-value pairs can be viewed within transaction traces in APM, traced errors in APM, transaction events in dashboards, and page views in dashboards.
attr_accessor: :tag_names
creates these two methods:
def tag_names
@tag_names
end
and
def tag_names=(value)
@tag_names=value
end
Because Ryan has his own tag_names
("reader") method he doesn't need to dynamically create it with attr_accessor
. He needs only the ("writer") method which is created by attr_writer
.
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