Thursday, April 28, 2011

How to watch a ruby class for method calls? (e.g. dependency injection, hooks, callbacks)

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?

From stackoverflow
  • 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..
    gsmendoza : Yep. "Observe" is the word I was looking for. Thanks! :)
  • Wouldn't it just work to do this:

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

    Hope this helps...

    reto : I think the OP will change the target class/object dynamically.
  • 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

0 comments:

Post a Comment