DEV Community

Cover image for Poor man's file watcher
olistik
olistik

Posted on

1

Poor man's file watcher

Image source

Suppose you want to perform a certain action each time one or more files change, for example running a spec each time they're updated.

You should definitely use something more polished like Guard but you could also experiment with a "simpler" approach.

First of all create the Ruby script check_event.rb:

# frozen_string_literal: true

last_mod = Time.now
loop do
  path_parts = gets.split
  path = "#{path_parts[0]}#{path_parts[2]}"
  next unless path.include?('_spec.rb')

  now = Time.now
  # Debounce: skip if another event has been notified less than a second ago.
  next if now - last_mod < 1

  last_mod = now
  puts `rspec "#{path}"`
end
Enter fullscreen mode Exit fullscreen mode

Make sure the command inotifywait is installed:

sudo apt install inotify-tools
Enter fullscreen mode Exit fullscreen mode

And then you can combine inotifywait with our Ruby script:

inotifywait --monitor --event modify --recursive ./spec | ruby check_event.rb
Enter fullscreen mode Exit fullscreen mode

Note: I added a debounce in the Ruby script. This is because a modify event is called twice upon file save (tested with Vim on Ubuntu).

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay