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
Class Method Summary collapse
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.
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 |
# File 'lib/filewatcher.rb', line 10 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 @deleted_files = [] end |
Class Method Details
.VERSION ⇒ Object
6 7 8 |
# File 'lib/filewatcher.rb', line 6 def self.VERSION return "0.2.1" end |
Instance Method Details
#expand_directories(filenames) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/filewatcher.rb', line 74 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
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/filewatcher.rb', line 48 def file_updated? @filenames.each do |filename| if(not(@deleted_files.include?(filename))) if(not(File.exist?(filename))) @deleted_files << filename @updated_file = filename @event = :delete return true end mtime = File.stat(filename).mtime updated = @last_mtimes[filename] < mtime @last_mtimes[filename] = mtime if(updated) @updated_file = filename @event = :changed return true end end end return false end |
#find(dir, filename = "*.*", subdirs = true) ⇒ Object
87 88 89 |
# File 'lib/filewatcher.rb', line 87 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
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/filewatcher.rb', line 37 def watch(sleep=1, &on_update) loop do begin Kernel.sleep sleep until file_updated? rescue SystemExit,Interrupt Kernel.exit end yield @updated_file, @event end end |