Class: FileWatcher
- Inherits:
-
Object
- Object
- FileWatcher
- Defined in:
- lib/filewatcher.rb
Overview
Simple file watcher. Detect changes in files and directories.
Issues: Currently doesn’t monitor changes in directorynames
Instance Method Summary collapse
- #expand_directories(filenames) ⇒ Object
- #file_updated? ⇒ Boolean
- #find(dir, filename = "*.*", subdirs = true) ⇒ Object
-
#initialize(filenames, print_filelist = false) ⇒ FileWatcher
constructor
A new instance of FileWatcher.
- #watch(sleep = 1, &on_update) ⇒ Object
Constructor Details
#initialize(filenames, print_filelist = false) ⇒ FileWatcher
Returns a new instance of FileWatcher.
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 |
# File 'lib/filewatcher.rb', line 6 def initialize(filenames,print_filelist=false) if(filenames.kind_of?String) filenames = [filenames] end filenames = (filenames) if(print_filelist) if(print_filelist.kind_of?String) puts print_filelist else puts "Watching:" end filenames.each do |filename| puts filename end end @last_mtimes = { } filenames.each do |filename| raise "File does not exist" unless File.exist?(filename) @last_mtimes[filename] = File.stat(filename).mtime end @filenames = filenames end |
Instance Method Details
#expand_directories(filenames) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/filewatcher.rb', line 52 def (filenames) files = [] filenames.each do |filename| if(File.directory?(filename)) files = files + find(filename) end if(File.file?(filename)) files << filename end end filenames = files end |
#file_updated? ⇒ Boolean
39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/filewatcher.rb', line 39 def file_updated? @filenames.each do |filename| mtime = File.stat(filename).mtime updated = @last_mtimes[filename] < mtime @last_mtimes[filename] = mtime if(updated) @updated_file = filename return true end end return false end |
#find(dir, filename = "*.*", subdirs = true) ⇒ Object
65 66 67 |
# File 'lib/filewatcher.rb', line 65 def find(dir, filename="*.*", subdirs=true) Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ] end |
#watch(sleep = 1, &on_update) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/filewatcher.rb', line 32 def watch(sleep=1, &on_update) loop do Kernel.sleep sleep until file_updated? yield @updated_file end end |