Skip to content

Instantly share code, notes, and snippets.

@riverock
Created November 22, 2013 14:30
Show Gist options
  • Save riverock/7600741 to your computer and use it in GitHub Desktop.
Save riverock/7600741 to your computer and use it in GitHub Desktop.
Sample script demonstrating that when starting two listeners, only the second listener responds to file system events
# Using Ruby 2.0.0p195 and listen 2.3.0
require 'listen'
require 'fileutils'
dir1 = '/Users/blue39/tmp/dir1'
FileUtils.remove_dir(dir1, true)
FileUtils.mkdir_p(dir1)
dir2 = '/Users/blue39/tmp/dir2'
FileUtils.remove_dir(dir2, true)
FileUtils.mkdir_p(dir2)
listener1 = Listen.to(dir1) do | modified, added, removed |
puts "listener1: modified: #{modified.inspect}, added: #{added.inspect}, removed: #{removed.inspect}"
end
listener2 = Listen.to(dir2) do | modified, added, removed |
puts "listener2: modified: #{modified.inspect}, added: #{added.inspect}, removed: #{removed.inspect}"
end
listener1.start
listener2.start
# Add a file to dir1
file_path = "#{dir1}/test.txt"
file = File.open(file_path, "w")
file.write("Testing")
file.close
sleep 1 # give listener1 time to respond to this file event
# Add a file to dir2
file_path = "#{dir1}/test.txt"
file = File.open(file_path, "w")
file.write("Testing")
file.close
sleep 1 # give listener2 time to respond to this file event
begin
listener1.stop
rescue SystemExit
puts "listener1: Eat #{$!.class} exception"
end
begin
listener2.stop
rescue SystemExit
puts "listener2: Eat #{$!.class} exception"
end
puts "Done!"
# The following appears in the console. Warning is triggered by stopping the second listner (line 17).
#
# listener2: modified: [], added: ["/Users/blue39/tmp/dir1/test.txt"], removed: []
# listener2: modified: ["/Users/blue39/tmp/dir1/test.txt"], added: [], removed: []
# listener1: Eat SystemExit exception
# [Listen warning]: Change block raised an exception: actor already terminated
# Backtrace:
# /Users/blue39/.rvm/gems/ruby-2.0.0-p195@listen_test/gems/celluloid-0.15.2/lib/celluloid/proxies/actor_proxy.rb:66:in `terminate!'
# /Users/blue39/.rvm/gems/ruby-2.0.0-p195@listen_test/gems/celluloid-0.15.2/lib/celluloid/proxies/actor_proxy.rb:59:in `terminate'
# /Users/blue39/.rvm/gems/ruby-2.0.0-p195@listen_test/gems/listen-2.2.0/lib/listen/listener.rb:158:in `_terminate_actors'
# /Users/blue39/.rvm/gems/ruby-2.0.0-p195@listen_test/gems/listen-2.2.0/lib/listen/listener.rb:141:in `_wait_for_changes'
# /Users/blue39/.rvm/gems/ruby-2.0.0-p195@listen_test/gems/listen-2.2.0/lib/listen/listener.rb:40:in `block in start'
# Done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment