Got it - maybe. I found a good resource[1], but I am not sure I
understand the value of the setter method in the first place. It would
seem that benefit is being able to skip explicitly calling save on an
object. Is that right?
The benefit of getter and setter methods are many - essentially they
allow you to perform operations on the variable before and after they
are retrieved or set. This is part of object-oriented methodology. But
in reference to your first question - "I was wondering what methods
ending in an equal sign meant", it is a feature of Ruby itself that
methods can end in "!", "?" and "=", and the community has taken these
to mean "potentially dangerous/exception creating", "interrogative
(should return a boolean)" and "sets a variable", respectively.
If I had this method defined on my class:
def my_attribute=(some_value)
@some_value = some_value
end
I could call:
@object.my_attribute = new_value
instead of:
@object.my_attribute = new_value
@object.save
Is that the reason to define a setter method?
No, because in #my_attribute=, you did not call save. Here is a reason
to define a setter method:
class Shape
def save_intersection=(shape)
@intersection = self.calculate_intersection(shape)
end
end
That is, we need to calculate the intersection of these two shapes and
then we can store the result in an instance variable. This is a good
use of the setter syntax, because it sets a variable, and we need to
do something "special". However, if we're not doing anything special
with the variable being set, it is preferable to write:
class Shape
attr_accessor :points
end
Which automatically defines the methods #points, which gets the
instance variable @points, and #points=, which will set the instance
variable if you used it like:
shape = Shape.new
shape.points = [1.2, 3,3]
Colin