watching a directory in ruby

点点圈 提交于 2019-11-28 19:14:13
Bill Turner

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...

msanjay

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:

  1. Added this to the gem file:

    gem 'listen', '~> 2.0'
    
  2. 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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!