Class: Tegawa::Watcher

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

Instance Method Summary collapse

Constructor Details

#initialize(watch_dir) ⇒ Watcher

Returns a new instance of Watcher.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tegawa/watcher.rb', line 7

def initialize(watch_dir)
  @queue = Tegawa.queue
  @logger = Tegawa.logger

  @logger.info "Watching #{watch_dir} for files"

  # TODO: maybe allow to specify extension and recursion?
  # listener = Listen.to("watch_dir", only: /.message$/) { |_modified, created, _removed|
  @listener = Listen.to(watch_dir) { |_modified, created, _removed|
    next if created.empty?

    consume_file(created)
  }
  @listener.start # not blocking
end

Instance Method Details

#consume_file(paths) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tegawa/watcher.rb', line 23

def consume_file(paths)
  paths.each do |path|
    next unless File.exist?(path)

    # FIXME: thread pool
    Thread.new {
      content = File.read(path)[0..4095]
      message = "File: #{path}\r\n\r\n#{content}"
      @queue << message
      File.delete(path)
    }
  end
end