Created: Wed May 28 08:37:12 UTC 2008
require 'pathname'

class SourceReload
  attr_accessor :interval

  def initialize(interval = 1)
    @interval = interval.to_f if interval
    @mtime = Hash.new{|h,k| h[k] = mtime(k) }
  end

  def start
    return unless interval
    iterate
  end

  def reload(file)
    mtime = mtime(file)
    unless @mtime[file] == mtime
      p file
      @mtime[file] = mtime
    end
  end

  def mtime(file)
    File.mtime(file)
  end

  def iterate
    loop do
      iteration do |file|
        reload(file)
      end
      # sleep interval
    end
  end

  def iteration
    files, paths = $",$:

    files.each do |file|
      if Pathname.new(file).absolute?
        yield file
      else
        paths.each do |path|
          abs = File.expand_path(File.join(path, file))
          if File.file?(abs)
            yield(abs)
            break
          end
        end
      end
    end
  end
end

SourceReload.new.start