class DirWait::Watch

Public: Watch the filesystem and wait for a directory to be created.

Public Class Methods

new(path) click to toggle source

Public: Initialize a new watcher.

path - The String path to watch.

# File lib/dirwait/watch.rb, line 25
def initialize(path)
  @watch_path = path
  @existing_parent = find_existing(path)
end

Public Instance Methods

find_existing(path) click to toggle source

Internal: Find the highest existing directory in a given path.

path - A String path to search.

Examples

find_existing('/usr/local/foo')
# => '/usr/local'

Returns the String path to the top-most existing directory.

# File lib/dirwait/watch.rb, line 40
def find_existing(path)
  until File.directory?(path)
    path = File.dirname(path)
  end
  path
end
start() click to toggle source

Public: Start the initialized listener.

Exits cleanly (exit code: 0) if @watch_path was created.

# File lib/dirwait/watch.rb, line 50
def start
  $stderr.puts "Watching filesystem events in: #{@existing_parent}"

  callback = Proc.new do |modified, added, removed|
    if added.any? {|i| File.fnmatch(@watch_path, i) }
      puts "Added: #{@watch_path}"
      exit 0
    end
  end

  listener = Listen.to(@existing_parent, ignore!: [], &callback)
  listener.start

  # Set trap so that we can break out of `sleep`
  Signal.trap("INT") do
    puts "Exiting..."
    exit 4
  end

  sleep
end