Class: Cline::Utils::FileMonitor

Inherits:
Object
  • Object
show all
Defined in:
lib/cline/utils/file_monitor.rb

Overview

Provide a file changes monitor. Calls a callback as a separate thread for each change that happens on a file

Instance Method Summary collapse

Constructor Details

#initialize(file, on_change:, monitoring_interval_secs: 1) ⇒ FileMonitor

Constructor

Parameters:

  • file (String)

    The file to monitor

  • on_change (#call)

    Block called each time there is an update.

    • Param mtime [Time, nil] The new file's modification time, or nil if the file is missing
  • monitoring_interval_secs (Float) (defaults to: 1)

    The monitoring interval in seconds



12
13
14
15
16
17
18
# File 'lib/cline/utils/file_monitor.rb', line 12

def initialize(file, on_change:, monitoring_interval_secs: 1)
  @file = file
  @on_change = on_change
  @monitoring_interval_secs = monitoring_interval_secs
  @monitoring = false
  @monitoring_thread = nil
end

Instance Method Details

#start { ... } ⇒ Object

Start monitoring

Yields:

  • Optional block that is called while monitoring has started. If this block is given, then #stop will be called automatically at the end of the block execution.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cline/utils/file_monitor.rb', line 24

def start
  @monitoring = true
  @monitoring_thread = Thread.new do
    file_mtime = nil
    loop do
      new_file_mtime = ::File.exist?(@file) ? ::File.mtime(@file) : nil
      if new_file_mtime != file_mtime
        # There is an update
        @on_change.call(new_file_mtime)
        file_mtime = new_file_mtime
      end
      break unless @monitoring

      sleep @monitoring_interval_secs
    end
  end
  return unless block_given?

  begin
    yield
  ensure
    stop
  end
end

#stopObject

Stop monitoring



50
51
52
53
# File 'lib/cline/utils/file_monitor.rb', line 50

def stop
  @monitoring = false
  @monitoring_thread.join
end