I was writing a script that does numerical differentiation, which required a lot of tweaking. I thought it would be quite cool to be able to see the results of the script automatically, whenever I made a change to the script, without having to run it again.
So I quickly wrote this up:
require 'digest/md5' $md5 = '' def watch(file, timeout, &cb) $md5 = Digest::MD5.hexdigest(File.read(file)) loop do sleep timeout if ( temp = Digest::MD5.hexdigest(File.read(file)) ) != $md5 $md5 = temp cb.call(file) end end end
That is the main function. It will wait for a fixed amount of time, get a hash of the file and compare it with a previous version. If it has changed, then it executes the callback which you have specified.
Here is an example of how it can be used:
$num = 0 watch '../num_diff.rb', 1 do |file| puts "\e[31m MODIFIED: \e[0m \e[34m #{file} \e[0m (#{$num}, #{Time.now})" puts "\e[32m -- EXECUTING -- \e[0m" puts puts `ruby #{file}` puts puts "\e[32m -- FINISHED EXECUTION -- \e[0m" puts $num += 1 end
