Listen

listen listens to file-changes in a directory.
You install it with gem install listen.

require 'listen'

lst = Listen.to('.') do |mod, add, rem|
  puts(mod: mod, add: add, rem: rem)
end

lst.start
sleep

I’m not sure right now if you need to lst.stop before quitting or if it takes care of itself when the main process dies.
Otherwise you could put the command in the ensure-block.. or trap signals and handle it there.

The code listens for changes in the current directory. If you open another terminal or use tmux.. and create a file in the same directory:

touch apa

The program will output:

{:mod=>[], :add=>["/path/to/dir/apa"], :rem=>[]}

One file added.

The listener can be started, stopped and paused with .start, .stop and .pause. State can be checked with .paused?, .processing?.
You can add to the ignore-list with .ignore /regx/ or replace the list with .ignore! /regx/. With .only /regx only the files matching will trigger a change.

Finally you find nice values for latency and wait_for_delay. Latency determines how often the directory will be scanned (default is 0.25 seconds). Wait_for_delay sets the time gap between callbacks (default 0.10 seconds).

  • Web page: GitHub
  • Author: Thibaud Guillaume-Gentil