Call method on attribute update

Hello,

I have an attribute in my class called @yn. If I change the value of @yn
by doing this:

foo.yn = 100.0

How do I cause another method in the class to automatically run? This is
what I want to do:

If @yn is updated, automatically run method "foo.calcArea". The way I
have it now requires me to do:

foo.yn = 100.0
foo.calcArea

There must be a way to let ruby call that method for me.

Thank you!

···

--
Posted via http://www.ruby-forum.com/.

If @yn is updated, automatically run method "foo.calcArea". The way I
have it now requires me to do:

foo.yn = 100.0
foo.calcArea

There must be a way to let ruby call that method for me.

Just define the attribute writer method yourself instead of using the helpers:

class Foo
  attr_reader :yn
  def yn=(value)
    @yn = value
    calcArea
  end

  def calcArea
     puts "recomputing area"
  end
end

f = Foo.new #=> #<Foo:0x1895458>
f.yn = 100 #=> 100

recomputing area

f.yn #=> 100

Gary Wright

···

On Oct 20, 2011, at 1:38 AM, Jason Lillywhite wrote:

Jason Lillywhite wrote in post #1027518:

Hello,

I have an attribute in my class called @yn. If I change the value of @yn
by doing this:

foo.yn = 100.0

How do I cause another method in the class to automatically run?

class Foo
  attr_accessor :yn

  # This is the general way to wrap a method call
  alias :old_yn= :yn=
  def yn=(val)
    self.old_yn = val
    puts "Yay!"
  end
end

foo = Foo.new
foo.yn = 123

···

--
Posted via http://www.ruby-forum.com/\.

If you find yourself doing that a lot, you could create a little utility:

class Class
    def attr_writer_with_callbacks attr, *callbacks
        instance_eval do
            define_method("#{attr}=") do |value|
                instance_variable_set "@#{attr}", value
                callbacks.each {|callback| send callback}
            end
        end
    end
end

ruby-1.8.7-p334 :038 > class A
ruby-1.8.7-p334 :039?> attr_writer_with_callbacks :test, :updated, :modified
ruby-1.8.7-p334 :040?> def updated
ruby-1.8.7-p334 :041?> puts "updated"
ruby-1.8.7-p334 :042?> end
ruby-1.8.7-p334 :043?> def modified
ruby-1.8.7-p334 :044?> puts "also modified"
ruby-1.8.7-p334 :045?> end
ruby-1.8.7-p334 :046?> end
=> nil
ruby-1.8.7-p334 :047 > A.new.test = "value"
updated
also modified
=> "value"

Jesus.

···

On Thu, Oct 20, 2011 at 8:01 AM, Gary Wright <gwtmp01@mac.com> wrote:

On Oct 20, 2011, at 1:38 AM, Jason Lillywhite wrote:

If @yn is updated, automatically run method "foo.calcArea". The way I
have it now requires me to do:

foo.yn = 100.0
foo.calcArea

There must be a way to let ruby call that method for me.

Just define the attribute writer method yourself instead of using the helpers:

class Foo
attr_reader :yn
def yn=(value)
@yn = value
calcArea
end

def calcArea
puts "recomputing area"
end
end

f = Foo.new #=> #<Foo:0x1895458>
f.yn = 100 #=> 100

recomputing area

f.yn #=> 100

Gary Wright