Skip to content

Instantly share code, notes, and snippets.

@jmcnevin
Last active January 1, 2016 07:49
Show Gist options
  • Save jmcnevin/8113767 to your computer and use it in GitHub Desktop.
Save jmcnevin/8113767 to your computer and use it in GitHub Desktop.
Using the Java 7 WatchService API with JRuby 1.7.9
require 'java'
class Watcher
java_import java.nio.file.FileSystems
java_import java.nio.file.StandardWatchEventKinds
IGNORE_PATHS = [
/\/vendor/,
/\/public/,
/\/tmp/,
/\.git/,
/\.bundle/,
/\.sass-cache/,
/\/log/
]
def initialize(path)
@fs = FileSystems.get_default
@watcher = @fs.new_watch_service
register_path(path)
start
end
def start
puts "Start"
begin
key = @watcher.take()
loop do
key.poll_events.each do |ev|
case ev.kind()
when StandardWatchEventKinds::ENTRY_CREATE
puts "Created: #{ev.context}"
when StandardWatchEventKinds::ENTRY_DELETE
puts "Deleted: #{ev.context}"
when StandardWatchEventKinds::ENTRY_MODIFY
puts "Modified #{ev.context}"
end
end
end
rescue => e
puts "Error: #{e}"
end
end
private
def ignore_path?(path)
IGNORE_PATHS.any? { |x| path =~ x }
end
def register_path(path, recursive = true)
return if ignore_path?(path)
puts "Register: #{path}"
dir = @fs.get_path(path)
dir.register(@watcher, StandardWatchEventKinds::ENTRY_CREATE,
StandardWatchEventKinds::ENTRY_DELETE,
StandardWatchEventKinds::ENTRY_MODIFY)
return unless recursive
Dir[File.join(path,'*','/')].each do |sub|
register_path(sub)
end
end
end
w = Watcher.new('/Users/jmcnevin/Source/fp2')
w.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment