Context: Many of the operations I’m doing require lengthy web accesses. Sometimes a web access fails and the process needs to be restarted. And it’s a pain to restart the process from scratch.
So I’ve written a number of ad-hoc approaches to checkpointing: when you restart the process, it looks to see if checkpoint data is available and re-initializes state from that, otherwise it creates fresh state. In the course of operation, the process periodically writes checkpoint data somewhere (to a file or to the db). And when it’s finished, it cleans up the checkpoint data.
I’d like a simple, DRY, general-purpose checkpointing mechanism. How would you write it? Or is there a module that already does this? (Though it’s not an issue yet, extra stars awarded for thread-safe implementations!)
After mulling it over, I deciding that I’m willing to make this specific to ActiveRecord. By exploiting ruby’s
ensurefacility and thedestroyed?andchanged?methods in ActiveRecord, the design becomes simple:define Checkpoint model with :name and :state
define WithCheckpoint module
sample usage
Here’s a somewhat contrived example that randomly blows up after some number of iterations. A more common case might be a lengthy network or file access that can fail at any point. Note: We store the state in an array only to show that ‘state’ needn’t be a simple integer.
When you run TestCheck.do_it, it might randomly blow up after some number of iterations. But you can re-start it until it completes properly: