Class: Jsus::Util::Watcher

Inherits:
Object
  • Object
show all
Defined in:
lib/jsus/util/watcher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_dirs, &callback) ⇒ Watcher

Instantiates a FSSM monitor and starts watching. Consider using class method Jsus::Util::Watcher.watch instead.

See Also:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/jsus/util/watcher.rb', line 20

def initialize(input_dirs, &callback)
  require 'fssm'
  @callback = callback
  input_dirs = Array(input_dirs).compact
  @semaphore = Mutex.new
  watcher = self
  FSSM.monitor do
    input_dirs.each do |dir|
      dir = File.expand_path(dir)
      path(dir) do
        glob ["**/*.js", "**/package.yml", "**/package.json"]
        create &watcher.method(:watch_callback)
        update &watcher.method(:watch_callback)
        delete &watcher.method(:watch_callback)
      end
    end
  end

rescue LoadError => e
  Jsus.logger.error "You need to install fssm gem for --watch option."
  Jsus.logger.error "You may also want to install rb-fsevent for OS X" if RUBY_PLATFORM =~ /darwin/
  raise e
end

Class Method Details

.watch(input_dirs) {|filename| ... } ⇒ FSSM::Monitor

Watches input directories and their subdirectories for changes in js source files and package metadata files.

Parameters:

  • input_dirs (String, Array)

    directory or directories to watch

Yields:

  • (filename)

    Callback to trigger on creation / update / removal of any file in given directories

Yield Parameters:

  • filename (String)

    Updated filename full path

Returns:

  • (FSSM::Monitor)

    fssm monitor instance



11
12
13
# File 'lib/jsus/util/watcher.rb', line 11

def watch(input_dirs, &callback)
  new(input_dirs, &callback)
end

Instance Method Details

#runObject



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jsus/util/watcher.rb', line 60

def run
  if @semaphore.try_lock
    begin
      yield
    rescue Exception => e
      Jsus.logger.error "Exception happened during watching: #{e}, #{e.inspect}"
      Jsus.logger.error "\t#{e.backtrace.join("\n\t")}" if Jsus.verbose?
      Jsus.logger.error "Compilation FAILED."
    ensure
      @semaphore.unlock
    end
  end
end

#running?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/jsus/util/watcher.rb', line 76

def running?
  @semaphore.locked?
end

#watch_callback(base, match) ⇒ Object

Note:

Defers the processing to a separate thread and ignores all the incoming events received during the processing.

Default callback for the FSSM watcher.

Parameters:

  • base (String)

    base part of filename

  • match (String)

    matched part of filename



50
51
52
53
54
55
56
57
# File 'lib/jsus/util/watcher.rb', line 50

def watch_callback(base, match)
  Thread.new do
    run do
      full_path = File.join(base, match)
      @callback.call(full_path)
    end
  end
end