There’s a lot of different reasons why you might want to have your Rails server restart whenever a file changes (we’re talking about development mode here hopefully). For me the reason was that I was doing some stuff with AR models inside of Threads which meant I needed to set “config.cache_classes = true” in development.rb. This means that all my AR classes are not reloaded on every request. Which means I need to restart the server whenever I change a model.
So here’s a little script I wrote to automatically restart the server whenever you change a .rb or .yml file anywhere in your rails dir (and all subdirs). I put this in a file called script/server_runner.
cmd = ARGV.shift || "script/server"
pid = nil
timestamps = {}
Thread.new do
while true
pid = fork { exec cmd }
Process.wait pid
end
end
while true
changed = []
Dir["./**/*.rb","./**/*.yml"].each do |f|
modified_at = File.stat(f).mtime
changed << f if timestamps[f] and modified_at != timestamps[f]
timestamps[f] = modified_at
end
if ! changed.empty?
puts "file(s) changed [#{changed.join(',')}], restarting"
Process.kill "INT", pid
end
sleep 1
end
Usage:
ruby script/server_runner
or
ruby script/server_runner script/some_other_server
And yes, obviously this solution sucks if your server takes more than a few seconds to start up.
