Skip to content

Instantly share code, notes, and snippets.

@fixlr
Created May 12, 2009 13:34
Show Gist options
  • Save fixlr/110480 to your computer and use it in GitHub Desktop.
Save fixlr/110480 to your computer and use it in GitHub Desktop.
#!/usr/local/env ruby
#
# Watch a set of files and open them in Safari and/or Firefox if they change.
# The files should probably be plain HTML files, but I'm not the boss of you.
# Refreshes index.htm or index.html by default (if they exist)
require 'optparse'
require 'ostruct'
options = OpenStruct.new
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] [files to watch]"
options.safari = true
options.firefox = false
options.index = "index.htm[l]?"
opts.on("-i", "--[no-]index",
"Specify the file to refresh whenever changes are found") do |i|
options.index = i
end
opts.on("-s", "--[no-]safari", "Reload the page(s) in Safari") do |s|
options.safari = s
end
opts.on("-f", "--[no-]firefox", "Reload the page(s) in Firefox") do |f|
options.firefox = f
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
command = "open -g"
# Decide which browsers need to be refreshed.
browsers = []
browsers << "Safari.app" if options.safari
browsers << "Firefox.app" if options.firefox
raise "No Browsers Selected" if browsers.length == 0
files = {}
ARGV.each do |arg|
Dir[arg].each do |file|
files[file] = File.mtime(file)
end
end
# Check to see if the file being refreshed is on the files list.
index_file = files.keys.find {|f| f =~ /#{options.index}/}
puts %{#{$0} is on the scene!
Currently watching #{files.collect {|k,v| File.basename(k)}.join(', ')}\n\n}
loop do
sleep 1
changed_file, last_changed = files.find do |file, last_changed|
File.mtime(file) > last_changed
end
if changed_file
files[changed_file] = File.mtime(changed_file)
puts "#{Time.now} => #{File.basename(changed_file)} changed"
browsers.each do |b|
system("#{command} -a #{b} #{index_file||changed_file}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment