tags:

views:

86

answers:

3

I have a Populater class for populating a database with random data. I would like to measure the populator's run method with the rtui progress bar. But instead of calling the progress bar object inside the Populater class, I would like to have a third class to increment the progress bar when certain methods in the Populater class are called. The code I have in mind is like this:

@populator = Populator.new
@pb = ProgressBar.new
Watcher.watch(@populator, :before, :add_record) do
  @pb.subject = "Adding a record..."
  @pb.inc
end

Watcher would call the watch block before executing @populator.add_record.

What's the best way to implement this?

A: 

I'd recommend you look at the observer pattern. I'd avoid fancy dynamic tricks before they are really necessary, the observer pattern is simple and pretty well understood.

Also checkout the Observable class in ruby's stdlib.

reto
You are looking for something generic *mmm*. you probably already know the observer pattern :). But yeah..
reto
Yep. "Observe" is the word I was looking for. Thanks! :)
gsmendoza
A: 

Wouldn't it just work to do this:

def watch(populator, when, dowhat)
    yield
    populator.add_record
end

Hope this helps...

norbertB
I think the OP will change the target class/object dynamically.
reto
+1  A: 

You might want to have a look at RCapture, a Ruby library that allows placing hooks on methods using a simple and consistent interface.

Christoph

Christoph Heindl