class FireflyServer::FileWatcher

Public Class Methods

new(configuration) click to toggle source
# File lib/firefly_server/file_watcher.rb, line 7
def initialize(configuration)
  @configuration = configuration
  @listener = nil
end

Public Instance Methods

watch!(&file_change_callback) click to toggle source
# File lib/firefly_server/file_watcher.rb, line 12
def watch!(&file_change_callback)
  # prevent multiple listeners
  listener.stop if listener
  # always mute the Listen logger due to verbosity
  if !Listen.logger
    Listen.logger = Logger.new(STDOUT)
    Listen.logger.level = Logger::WARN
  end
  @listener = Listen.to(*configuration.watch_paths) do |modified, added, removed|
    ignored = []
    [modified, added, removed].each do |paths|
      # remove ignored paths
      paths.reject! do |path|
        configuration.ignore_paths.any? do |ignore_path|
          is_ignored =
            case ignore_path
            when String then path.start_with?(ignore_path)
            when Regexp then path =~ ignore_path
            else
              raise(
                ArgumentError,
                "unknown ignore path (expected string or regex): #{ignore_path.class} - #{ignore_path.inspect}"
              )
            end
          ignored << path if is_ignored
        end
      end
    end
    # trigger change callbacks
    callbacks = (configuration.file_change_callbacks + [file_change_callback]).compact
    if !callbacks.empty?
      change_event = ChangeEvent.new(ignored: ignored, modified: modified, added: added, removed: removed)
      callbacks.each do |callback|
        callback.call(change_event)
      end
    end
  end
  listener.start
  self
end