Skip to content

Instantly share code, notes, and snippets.

@paulrayner
Created March 2, 2013 23:41
Show Gist options
  • Select an option

  • Save paulrayner/5073777 to your computer and use it in GitHub Desktop.

Select an option

Save paulrayner/5073777 to your computer and use it in GitHub Desktop.
AsciiWatcher - live preview one or more AsciiDoc files in Chrome using Asciidoctor to render to HTML and AppleScript to perform the browser tab refresh. Adapted from watch.rb by Brett Terpstra (with credit to Carlo Zottmann).
#!/usr/bin/env ruby
# AsciiWatcher by Paul Rayner, 2013 <http://thepaulrayner.com>
# Adapted from watch.rb by Brett Terpstra, 2011 <http://brettterpstra.com>
# with credit to Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher>
require 'asciidoctor'
trap("SIGINT") { exit }
if ARGV.length < 2
puts "Usage: #{$0} watch_folder keyword stylesheet"
puts "Example: #{$0} . mywebproject github.css"
exit
end
dev_extension = 'dev'
filetypes = ['css','html','htm','php','rb','erb','less','js','asc']
watch_folder = ARGV[0]
keyword = ARGV[1]
stylesheet = ARGV[2]
puts "Watching #{watch_folder} and subfolders for changes in project files"
puts "Will refresh any Chrome browser tab with URL containing '#{keyword}' using"
puts "specified stylesheet"
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
diff_hash.each do |df|
asciidoc_file_name = df[0]
puts "Detected change in #{asciidoc_file_name}"
type = File.extname(asciidoc_file_name).gsub(/^\./, '')
if type == "asc"
Asciidoctor.render_file(asciidoc_file_name, :in_place => true, :attributes => {'stylesdir' => 'styles', 'stylesheet' => stylesheet})
puts "Rendered AsciiDoc to HTML"
else
puts "Refreshing Chrome tab matching #{keyword}"
%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
end
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment