· 8 years ago · Feb 20, 2018, 11:48 PM
1#!/usr/bin/env ruby
2#
3# Name: reval.rb
4# License: MIT
5# Author: postmodern (postmodern.mod3 at gmail.com)
6# Description:
7#
8# Re-evaluates a specified Ruby file whenever the file changes.
9# Reval was inspired by Giles Bowkett's kickass talk on Archaeopteryx at
10# RubyFringe 2008, where Giles used some mad Ruby to re-evaluate his
11# Achaeopteryx script as he edited it.
12#
13# Reval might come in handy, when you give that awesome breakthrough talk
14# at some conference.
15#
16
17require 'digest/md5'
18
19#
20# Re-evaluate the contents of the specified _file_, whenever the file
21# changes, using the given _options_.
22#
23# _options_ may contain the following keys:
24# <tt>:pause</tt>:: Number of seconds to sleep between checking the _file_
25# for changes. Defaults to +0.4+ if not given.
26#
27# reval 'file.rb'
28#
29# reval 'file.rb', :pause => 0.4
30#
31def reval(file,options={})
32 pause = (options[:pause] || 0.4)
33
34 last_time = Time.now
35 this_time = Time.now
36
37 last_fingerprint = nil
38 fingerprint = nil
39
40 if File.file?(file)
41 last_fingerprint = Digest::MD5.hexdigest(File.read(file))
42
43 load(file)
44 end
45
46 loop do
47 begin
48 this_time = File.mtime(file)
49
50 if (this_time > last_time)
51 fingerprint = Digest::MD5.hexdigest(File.read(file))
52
53 if last_fingerprint != fingerprint
54 load(file)
55
56 last_fingerprint = fingerprint
57 end
58
59 last_time = this_time
60 end
61 rescue Errno::ENOENT
62 end
63
64 sleep(pause)
65 end
66end
67
68reval(ARGV[0]) if ($0 =~ /reval/ && ARGV[0])