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
end
#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.

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

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

#2
You could use the kvo gem: https://github.com/shawn42/kvo It is
generally
intended for external things to watch for attribute changes, but could
be
used on itself.

The caveat being that you don’t access the instance variables directly,
but
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 }
end

def update_total
@total = att1 + att2 + att3
end
end

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

Good luck
/Shawn

Thank’s for your help.
:slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs