如何使用ruby检测文件系统事件

n-n*_*awa 3 ruby filesystems events

我想使用ruby来查看文件和目录的文件系统事件.

现在我正在使用Guard.但它只检测文件事件.

有没有办法检测包括目录事件在内的文件系统事件?

MId*_*hna 6

您可以rb-inotify来查看特定目录的文件系统事件,例如:

require "rb-inotify"

DIR_TO_WATCH = "/tmp/notify-dir"

notifier = INotify::Notifier.new

notifier.watch(DIR_TO_WATCH, :create, :delete) do |event|
  puts "Create event for: #{event.name}" if event.flags.include?(:create)
  puts "Delete event for: #{event.name}" if event.flags.include?(:delete)
end

notifier.run
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

编辑

为了支持多个平台,您可以尝试使用Listen,这是由Guard的人员制作的,支持Mac OS X 10.6 +,Linux,BSD(有些问题)和Windows.

来自文档:

listener = Listen.to('dir/to/listen', 'dir/to/listen2') do |modified, added, removed|
  puts "modified absolute path: #{modified}"
  puts "added absolute path: #{added}"
  puts "removed absolute path: #{removed}"
end
listener.start # not blocking
sleep
Run Code Online (Sandbox Code Playgroud)