Lee Quarella
Lee Quarella

Reputation: 4742

Rails detect changes to files programatically

I would like to write a method that programatically detects whether any of the files in my rails app have been changed. Is it possible do do something like an MD5 of the whole app and store that in a session variable?

This is mostly for having some fun with cache manifest. I already have a dynamically generated cache and it works well in production. But in my dev environment, I would like the id of that cache to update whenever I change anything in the app directory (as opposed to every 10 seconds, which is how I have it setup right now).

Update

File.ctime(".") would be perfect, except that "." is not marked as having changed when deeper directory files have changed.

Does it make sense to iterate through all directories in "." and add together the ctimes for each?

Upvotes: 1

Views: 3719

Answers (3)

thomasfl
thomasfl

Reputation: 159

There is a simple ruby gem called filewatcher. This is the most advanced example:

require 'filewatcher'

FileWatcher.new(["README.rdoc"]).watch() do |filename, event|
  if(event == :changed)
    puts "File updated: " + filename
  end
  if(event == :delete)
    puts "File deleted: " + filename
  end
  if(event == :new)
    puts "New file: " + filename
  end
end

Upvotes: 2

Lee Quarella
Lee Quarella

Reputation: 4742

File.ctime is the key. Iterate through all files and create a unique id based on the sum of all their ctimes:

cache_id = 0
Dir.glob('./**/*') do |this_file|
   ignore_files = ['.', '..', "log"]
   ignore_files.each do |ig|
       next if this_file == ig
   end
   cache_id += File.ctime(this_file).to_i if File.directory?(this_file)
end

Works like a charm, page only re-caches when it needs to, even in development.

Upvotes: 0

diedthreetimes
diedthreetimes

Reputation: 4113

Have you considered using Guard.

You can programatically do anything whenever a file in your project changes.

There is a nice railscast about it

Upvotes: 4

Related Questions