Class: Slinky::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/slinky/listener.rb

Instance Method Summary collapse

Constructor Details

#initialize(manifest, livereload) ⇒ Listener

Returns a new instance of Listener.



5
6
7
8
# File 'lib/slinky/listener.rb', line 5

def initialize manifest, livereload
  @manifest = manifest
  @livereload = livereload
end

Instance Method Details

#handle_add(files) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/slinky/listener.rb', line 49

def handle_add files
  begin
    @manifest.add_all_by_path files
  rescue
    puts "Unable to add file: #{$!}"
  end
end

#handle_mod(files) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/slinky/listener.rb', line 41

def handle_mod files
  begin
    @manifest.update_all_by_path files
  rescue
    puts "Unable to update file: #{$!}"
  end
end

#handle_rem(files) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/slinky/listener.rb', line 57

def handle_rem files
  begin
    @manifest.remove_all_by_path files
  rescue
    puts "Unable to remove file: #{$1}"
  end
end

#runObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/slinky/listener.rb', line 10

def run
  manifest_md5 = @manifest.md5
  listener = Listen.to(@manifest.dir) do |mod, add, rem|

    EM.next_tick {
      handle_mod(mod) if mod.size > 0
      handle_add(add) if add.size > 0
      handle_rem(rem) if rem.size > 0
      
      files = (mod + add + rem).map{|path|
        mpath = Pathname.new(path)\
          .relative_path_from(Pathname.new(@manifest.dir).expand_path).to_s
        mf = @manifest.find_by_path(mpath, false).first
        if mf
          mf.output_path
        else
          nil
        end
      }.compact

      # only reload if something's actually changed
      if manifest_md5 != @manifest.md5 && files.size > 0
        manifest_md5 = @manifest.md5
        @livereload.reload_browser(files)
      end
    } if @livereload
  end
  listener.start
  listener
end