We have an application that needs to process incoming files that are dropped into a directory. I am looking for the best way to do this.
We have been using a loopin
Thanks @emerge, as a relative newbie to rails I wanted to watch for files in my Rails app and not from the command line. Compared to the other options here, found that Listen was an incredibly simple 2 steps:
Added this to the gem file:
gem 'listen', '~> 2.0'
Then added this in Application.rb to execute on app startup:
listener = Listen.to('public/json_import') do |added|
puts "added absolute path: #{added}"
end
listener.start # not blocking
We can also listen to multiple dirs, and also modify/add/remove:
listener = Listen.to('dir/to/listen', 'dir/to/listen2') do |modified, added, removed|
There's also the tiny filewatcher rubygem. The gem has no dependencies, contains no platform specific code and simply detects updates, delitions and additions by polling.
require 'filewatcher'
FileWatcher.new(["directory"]).watch() do |filename, event|
if(event == :changed)
puts "File updated: " + filename
end
if(event == :delete)
puts "File deleted: " + filename
end
if(event == :new)
puts "Added file: " + filename
end
end
Three old-school options that I know of:
Ara T. Howard's DirWatch:
My own DirectoryWatcher:
Paul Horman's FileSystemWatcher:
And there's also guard:
Guard automates various tasks by running custom rules whenever file or directories are modified.
It's frequently used by software developers, web designers, writers and other specialists to avoid mundane, repetitive actions and commands such as "relaunching" tools after changing source files or configurations.
Common use cases include: an IDE replacement, web development tools, designing "smart" and "responsive" build systems/workflows, automating various project tasks and installing/monitoring various system services...
https://github.com/mynyml/watchr
That's typically used for running unit test automatically but should suit your needs too.
I think https://github.com/nex3/rb-inotify should work for you. An example to use this gem
require 'rb-inotify'
notifier = INotify::Notifier.new
notifier.watch("/tmp", :moved_to, :create) do |event|
puts "#{event.absolute_name} is now in path /tmp!"
end
notifier.run