Skip to content

Instantly share code, notes, and snippets.

@gokhandemirhan
Last active May 10, 2017 11:47
Show Gist options
  • Save gokhandemirhan/24b5571f9efa9563acabd28d87c277e1 to your computer and use it in GitHub Desktop.
Save gokhandemirhan/24b5571f9efa9563acabd28d87c277e1 to your computer and use it in GitHub Desktop.
refresh chrome when a file changed in specified directory
#!/usr/bin/env ruby
# watch.rb by Brett Terpstra, 2011 <http://brettterpstra.com>
# with credit to Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher>
# http://brettterpstra.com/2011/03/07/watch-for-file-changes-and-refresh-your-browser-automatically/
trap("SIGINT") { exit }
class String
# colorization
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def pink
colorize(35)
end
def light_blue
colorize(36)
end
end
if ARGV.length < 2
puts "Usage: #{$0} watch_folder keyword"
puts "Example: #{$0} . mywebproject"
exit
end
filetypes = ['css','html','htm','php','rb','erb','less','js','inc']
watch_folder = ARGV[0]
keyword = ARGV[1]
puts "** Watching #{watch_folder} and subfolders for changes in project files...".blue
while true do
files = []
filetypes.each {|type|
files += Dir.glob( File.join( watch_folder, "**", "*.#{type}" ) )
}
new_hash = files.collect {|f| [ f, File.stat(f).mtime.to_i ] }
hash ||= new_hash
diff_hash = new_hash - hash
unless diff_hash.empty?
hash = new_hash
sleep 0.5
diff_hash.each do |df|
puts "** Detected change in #{df[0]}, refreshing".green
%x{osascript<<ENDGAME
tell application "Google Chrome"
set windowList to every window
repeat with aWindow in windowList
set tabList to every tab of aWindow
repeat with atab in tabList
if (URL of atab contains "#{keyword}") then
tell atab to reload
end if
end repeat
end repeat
end tell
ENDGAME
}
end
end
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment