class Sasquatch::Listener

Attributes

base_path[R]
file[R]
file_changed[R]
files[R]
listener[R]
running[R]
status[R]

Public Class Methods

new(file, running = true, &block) click to toggle source
# File lib/quatch/listener.rb, line 8
def initialize file, running = true, &block
  @file = file

  @base_path = File.dirname(@file)

  @running = running

  validate_file @file

  find_imports @file

  @file_changed = block

  # init the logger
  logger "Watching '#{@file}' for updates"

  # listen to the main file's directory
  @listener = Listen.to(File.dirname(@file), only: /\.js$/, &hear)
  # start listening
  start
end

Public Instance Methods

_get_file_name(filename) click to toggle source
# File lib/quatch/listener.rb, line 82
def _get_file_name filename
  filename.sub(/^.*?#{@base_path}\//, '')
end
find_imports(file) click to toggle source
# File lib/quatch/listener.rb, line 30
def find_imports file
  @files = {}
  File.read(file).scan(/\/\* @import .+?(.*.js)/) do |filename|
    @import = "#{File.dirname(@file)}/#{filename.first}"
    validate_file @import
    @files[filename.first] = File.new(File.absolute_path(@import))
  end
end
hear() click to toggle source
# File lib/quatch/listener.rb, line 39
def hear
  Proc.new do |modified, added, removed|
    if(modified)
      modified_file = modified.first
      if(imported? modified_file)
        if(@file_changed)
          @file_changed.call(_get_file_name(modified_file), @file, @files)
        end
      end
    end
  end
end
imported?(file) click to toggle source
# File lib/quatch/listener.rb, line 70
def imported? file

  filename = _get_file_name file

  if(filename == _get_file_name(@file) or @files.keys.include? filename)
    return true
  end

  false

end
start() click to toggle source
# File lib/quatch/listener.rb, line 52
def start
  @listener.start # not blocking
  while( @running ) do
    sleep(1)
  end
end
stop() click to toggle source
# File lib/quatch/listener.rb, line 59
def stop
  @listener.pause
  @running = false
end
validate_file(file) click to toggle source
# File lib/quatch/listener.rb, line 64
def validate_file file
  unless(File.file?(file))
    raise "Specified file doesn't exist"
  end
end