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

I have a Populater class to populate a database with random data. I would like to measure the start method of a populator with a rtui progress bar. But instead of calling the progress bar object inside the Populater class, I would like to have a third class to increase the progress bar when certain methods in the Populater class are called. The code I mean looks like this:

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

      

The observer will call the clock block before executing @ populator.add_record.

What's the best way to implement this?

0


a source to share


3 answers


I would recommend that you look at the observer pattern . I would avoid fancy dynamic tricks before actually needed, the observer pattern is simple and fairly well understood.



Also check Observable class in ruby ​​stdlib.

0


a source


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



Christoph

+1


a source


Wouldn't this just work:

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

      

Hope it helps ...

0


a source







All Articles