Sha256: 8627d920d8d0a9a7bed8c89c11cbc5aeb635427c7a9e0338742ac0f719bd1aaa

Contents?: true

Size: 1.46 KB

Versions: 4

Compression:

Stored size: 1.46 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|
        if @options.verbose
          watch_settings.each {|ws| puts "Watching #{ws}" }
        end
        @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

4 entries across 4 versions & 1 rubygems

Version Path
dirwatch-0.0.9 lib/dirwatch/watcher.rb
dirwatch-0.0.8 lib/dirwatch/watcher.rb
dirwatch-0.0.7 lib/dirwatch/watcher.rb
dirwatch-0.0.6 lib/dirwatch/watcher.rb