def watch_and_run(monitor, times, recursively, directory, *flags)
      result = OpenStruct.new(directory: directory, changes: [])
      i = 0
      result.changes[i] = OpenStruct.new(called: false)
      can_return = false
      callback = Proc.new do |change|
        next if can_return

        result.changes[i].called = true;
        result.changes[i].change = change

        i += 1

        if i < times
          result.changes[i] = OpenStruct.new(called: false)
        else
          can_return = true
        end
      end

      if recursively
        monitor.watch_recursively(directory, *flags, &callback)
      else
        monitor.watch(directory, *flags, &callback)
      end

      thread = Thread.new(monitor) { |m| m.run! }
      sleep(0.2) # give time for the monitor to bootup

      yield # So much boilerplate code to get here :S

      sleep(0.2) # allow the monitor to run the callbacks

      # Nothing can change after the callback if there is only one of them,
      # so never wait for one callback
      if times > 1
        until can_return
          sleep(0.1)
        end
      end

      return result
    ensure
      monitor.stop
      thread.join if thread
    end
def watch_and_run(monitor, times, recursively, directory, *flags)
      result = OpenStruct.new(directory: directory, changes: [])
      i = 0
      result.changes[i] = OpenStruct.new(called: false)
      can_return = false
      callback = Proc.new do |change|
        next if can_return

        result.changes[i].called = true;
        result.changes[i].change = change

        i += 1

        if i < times
          result.changes[i] = OpenStruct.new(called: false)
        else
          can_return = true
        end
      end

      if recursively
        monitor.watch_recursively(directory, *flags, &callback)
      else
        monitor.watch(directory, *flags, &callback)
      end

      thread = Thread.new(monitor) { |m| m.run! }
      sleep(0.2) # give time for the monitor to bootup

      yield # So much boilerplate code to get here :S

      sleep(0.2) # allow the monitor to run the callbacks

      # Nothing can change after the callback if there is only one of them,
      # so never wait for one callback
      if times > 1
        until can_return
          sleep(0.1)
        end
      end

      return result
    ensure
      monitor.stop
      thread.join if thread
    end
Very customizable method to watch directories and then run the monitor

 @yield