# $Id: autoreload.rb,v 1.3 2004/04/22 14:47:49 eto Exp $
# Copyright (C) 2001-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'singleton'
require 'thread'

class AutoReload
  include Singleton
  def initialize
    @status = {}
    @thread = nil
    @debug = false
  end
  attr_accessor :debug

  def autoreload(interval)
    @thread = Thread.new {
      loop {
	update
	sleep interval
      }
    }
  end

  private

  def update
    $".each {|lib|
      if @status[lib]
	file, mtime = @status[lib]
	now = File.mtime(file).to_i
	if mtime < now
	  load file
	  @status[lib] = [file, now]
	  $stderr.print "reload: \"#{file}\"\n" if @debug
	end
      else
	@status[lib] = get_status(lib)
	break if @status[lib]
	$LOAD_PATH.each {|path|
	  @status[lib] = get_status(File.join(path, lib))
	  break if @status[lib]
	}
      end
    }
  end

  def get_status(file)
    FileTest.exist?(file) ? [file, File.mtime(file).to_i] : nil
  end
end

def autoreload(interval, debug = false)
  ar = AutoReload.instance
  ar.debug = debug
  ar.autoreload(interval)
end
