Sha256: ab782028b2ea0be4d5105f1d9b6e47d5d017f1ab2e94130929db85c3a33b0afb

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

require_relative 'settings'

module Dirwatch
  class Watcher
    attr_reader :options
    attr_reader :settings

    def initialize options
      @options = options
      @settings = Settings.from_options @options

      return unless options.daemonize
      Process.daemon true, true
      puts "running in the background... [#{Process.pid}]"
    end

    def start
      raise 'already started' if @threads
      @threads = []
      @stop = false

      Thread.abort_on_exception = true
      @settings.by_interval do |interval, watch_settings|
        watch_settings.each {|ws| puts "Watching #{ws}" }
        @threads << Thread.new do
          run interval, watch_settings
        end
      end
    end

    def wait_for_stop
      @threads.each(&:join)
    end

    def stop
      raise 'not started' unless @threads
      @stop = true
      wait_for_stop
    end

    def files
      Dir[File.join options.directory, '**', options.file_match]
    end

    private

    def run interval, watch_settings
      change_times = []
      until @stop
        watch_settings.each.with_index do |ws, i|
          change_time = ws.files.map {|f| File.ctime f }.max
          next if change_time == change_times[i]
          puts "Changed: #{ws.key}" if options.verbose
          change_times[i] = change_time
          ws.exec_scripts options.verbose
        end

        break if @stop || options.once
        sleep interval
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dirwatch-0.0.5 lib/dirwatch/watcher.rb
dirwatch-0.0.4 lib/dirwatch/watcher.rb