Reputation: 8622
I have two Ruby files: exec.rb and lib.rb. lib.rb is required by exec.rb. Every time I modify lib.rb, I need to restart exec.rb.
Is it possible to have exec.rb reload lib.rb while running?
Upvotes: 1
Views: 1101
Reputation: 160631
It's possible to do this using File.mtime
and comparing the last-modified timestamp for lib.rb.
In your code, get the mtime
when you first load the file:
last_mtime = File.mtime('lib.rb')
load 'lib.rb'
Later, in a loop as you process, check again to see if the modification time changed, and reload if necessary:
current_mtime = File.mtime('lib.rb')
if (current_mtime != last_mtime)
last_mtime = current_mtime
load 'lib.rb'
end
I've used a similar technique in the past, and it worked well. I set mine up so it only checked every five minutes, but your needs might be different.
Upvotes: 1
Reputation: 230561
You can subscribe to file change notifications. Here's a lib for osx: rb-fsevent.
When you get notification that the file changed, you can reload it.
filename = './lib.rb' # get file name from event
load filename
You should use load
instead of require
, because require
loads file only once and then does not load it again.
Upvotes: 1