Search code examples
ruby-on-railsrubyguardwatch

Update database when a file changed in public/ with rails


I would like to be able to update my database when a file in public/ is modified. The rails app use file pushed by an old system and we need to update the internal database with theses change.

Is this possible and how can i do this. I checked for guard, but is it usable in production ? Is there a better alternative ? Maybe i can just use dnotify, but i would like to keep everything in my project aka all in ruby and without external programs.

Thanks :P


Solution

  • Guard uses a gem called listen underneath which implements the generic notifications and interfaces with the various OS modules.

    Listen supports:

    • Linux via rb-inotify
    • Darwin via rb-fsevent
    • Windows via wdm (mingw, not cygwin)
    • BSD(sortof) via rb-kqueue
    • Polling the file system every second via Ruby is the fall back option.

    The modules are all basically thin veneers allowing access to the underlying OS notification system calls. You could code one of the OS specific modules directly if you want, but why would you when someone has already given you a generic interface?

    Listen is fairly simple to use:

    listener = Listen.to('dir/path/to/listen') do |modified, added, removed|
       puts "mod: #{modified}" if modified
       puts "add: #{added}"    if added
       puts "rem: #{removed}"  if removed
    end
    listener.start
    

    You can use polling at a higher interval if you have concerns or issues with the FFI/C modules

    options = {
      force_polling: true,
      latency:       30 
    }
    

    Then integrate the code to run alongside your rails app with daemons-rails