Attributes values influences another attribute

Ey guys, how are you? I’m wondering if you can give me your advice.
First the problem:

attr_accessor :attribute1 :attribute2 :attribute3
@attribute1 = 3
@attribute2 = 5
@attribute3 = 1
@total = 9
#this last attribute must be the result of the summation of @attribute1

  • #@attribute2 + @attribute3.

So what’s the best way to reflect the explained in the comments inside
the code. Will be very nice if i can assign the value of attribute1, 2
or 3 with the attr_accessor facility. How can the value of @total be
refreshed when one of attribute1, 2 or 3 has his value changed? I though
in do(instead of the attr_accessor facility) one writer method for each
of the 3 attribute, like this:

def change_attribute1(new_value)
@total = @attribute2 + @attribute3 + new_value
@attribute1 = new_value
#and so on with the others attributes

but this seems sicken. Is there any way to link the values of the
attributes with @total with the attr_accessor facility or other way…or
I’m just limited to the last option. Thank’s for your time. Damián.

You could also just calculate total whenever it’s asked for:

class Thing
attr_accessor :att1, :att2, :att3
def total
@att1 + @att2 + @att3

You could use the kvo gem: GitHub - shawn42/kvo: KVO in Ruby It is
intended for external things to watch for attribute changes, but could
used on itself.

The caveat being that you don’t access the instance variables directly,
must set them via their setter method.

class Thing
include Kvo
kvo_attr_accessor :att1, :att2, :att3
def initialize
self.when :attr1_changed { update_total }
self.when :attr2_changed { update_total }
self.when :attr3_changed { update_total }

def update_total
@total = att1 + att2 + att3

If you are only calculating a quick sum, option #1 should suffice. If
are actually doing some complicated thing that needs to only be
once, #2 would work. Option #3 (not shown) would be to just write the
setter methods your self for att1=, att2= … etc

Good luck

Thank’s for your help.