# Continually running a script with Ruby and Watchr

I’m currently working through Ruby Koans, which involves editing some .rb files, running a build and watching the output for hints on what change to make next. It’s quite a fun mix of TDD and puzzle solving. I did start to find constantly rebuilding after each change a bit laborious though, so I thought I’d look at automating it (Autotest style).

After floundering around Google for a while I asked Twitter and @joshnesbitt helped me out, suggesting I try Watchr. After installing the gem, I ending up putting the following auto_enlighten.rb script in the koans directory:

require 'rubygems'
require 'watchr'

all_rb = Dir['*.rb'].join('|')
script = Watchr::Script.new
script.watch( all_rb ) { |file| system("rake") }
controller = Watchr::Controller.new(script, Watchr.handler.new)
controller.run


This script selects all .rb files in the current directory and tells the Watchr script to run rake (to build the koans and get the next hint) whenever one of those files changes. I then can run ruby auto_enlighten.rb from my terminal and hack away happily in vim, and each time I save a file I get near-instant feedback on how my change affected my progress through the koans. I’ve found this a very nice way to work through the koans.

Watchr also has some scripts for common tasks like running tests and specs, can be run from the command line, or can be used programmatically as we’re doing here. Definitely worth checking out. :)