Method: EventMachine.watch_file

Defined in:
lib/eventmachine.rb

.watch_file(filename, handler = nil, *args) ⇒ Object

Note:

The ability to pick up on the new filename after a rename is not yet supported. Calling #path will always return the filename you originally used.

EventMachine's file monitoring API. Currently supported are the following events on individual files, using inotify on Linux systems, and kqueue for *BSD and Mac OS X:

  • File modified (written to)
  • File moved/renamed
  • File deleted

EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods. This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch object with your Module mixed in. FileWatch is a subclass of Connection, so callbacks on this object work in the familiar way. The callbacks that will be fired by EventMachine are:

  • file_modified
  • file_moved
  • file_deleted

You can access the filename being monitored from within this object using EventMachine::FileWatch#path.

When a file is deleted, EventMachine::FileWatch#stop_watching will be called after your file_deleted callback, to clean up the underlying monitoring and remove EventMachine's reference to the now-useless FileWatch instance. This will in turn call unbind, if you wish to use it.

The corresponding system-level Errno will be raised when attempting to monitor non-existent files, files with wrong permissions, or if an error occurs dealing with inotify/kqueue.

Examples:


# Before running this example, make sure we have a file to monitor:
# $ echo "bar" > /tmp/foo

module Handler
  def file_modified
    puts "#{path} modified"
  end

  def file_moved
    puts "#{path} moved"
  end

  def file_deleted
    puts "#{path} deleted"
  end

  def unbind
    puts "#{path} monitoring ceased"
  end
end

# for efficient file watching, use kqueue on Mac OS X
EventMachine.kqueue = true if EventMachine.kqueue?

EventMachine.run {
  EventMachine.watch_file("/tmp/foo", Handler)
}

# $ echo "baz" >> /tmp/foo    =>    "/tmp/foo modified"
# $ mv /tmp/foo /tmp/oof      =>    "/tmp/foo moved"
# $ rm /tmp/oof               =>    "/tmp/foo deleted"

Parameters:

  • filename (String)

    Local path to the file to watch.

  • handler (Class, Module) (defaults to: nil)

    A class or module that implements event handlers associated with the file.



1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
# File 'lib/eventmachine.rb', line 1309

def self.watch_file(filename, handler=nil, *args)
  klass = klass_from_handler(FileWatch, handler, *args)

  s = EM::watch_filename(filename)
  c = klass.new s, *args
  # we have to set the path like this because of how Connection.new works
  c.instance_variable_set("@path", filename)
  @conns[s] = c
  block_given? and yield c
  c
end