Skip to content

Commit

Permalink
Add Watcher.scan and event.status
Browse files Browse the repository at this point in the history
  • Loading branch information
faustinoaq committed Mar 30, 2017
1 parent 42bf248 commit efc287d
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions src/watcher.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ module Watcher
TIMESTAMPS = {} of String => String

private class WatchEvent
property change = false, files = {} of String => String
property status = false, files = {} of String => String
def on_change
yield files if change
yield files if status
end
end

Expand All @@ -15,31 +15,40 @@ module Watcher
File.stat(file).mtime.to_s("%Y%m%d%H%M%S")
end

private def self.scan(files, event)
event.status = false
Dir.glob(files) do |file|
timestamp = timestamp_for(file)
if TIMESTAMPS[file]? && TIMESTAMPS[file] != timestamp
TIMESTAMPS[file] = timestamp
event.status = true
event.files[file] = timestamp
puts "🤖 #{file}"
elsif TIMESTAMPS[file]?.nil?
TIMESTAMPS[file] = timestamp
event.status = true
event.files[file] = timestamp
puts "🤖 watching file: #{file}"
end
end
event
end

# Allow to watch file changes using Watcher.watch
def self.watch(files)
files = Dir.glob(files)
files.each do |file|
TIMESTAMPS[file] = timestamp_for(file)
end
event = WatchEvent.new
loop do
event.change = false
event.files.clear
files.each do |file|
timestamp = timestamp_for(file)
if TIMESTAMPS[file]? != timestamp
TIMESTAMPS[file] = timestamp
event.change = true
event.files[file] = timestamp
end
end
event = Watcher.scan(files, event)
yield event
event.files.clear
sleep 1
end
end
end

# Allow to watch file changes
def watch(files)
Watcher.watch(files)
Watcher.watch(files) do |event|
yield event
end
end

0 comments on commit efc287d

Please sign in to comment.