postmodern (owner)

Revisions

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