Skip to content

Instantly share code, notes, and snippets.

@bf4
Last active December 28, 2015 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bf4/7531475 to your computer and use it in GitHub Desktop.
Save bf4/7531475 to your computer and use it in GitHub Desktop.
highlight files
#!/usr/bin/env ruby
# Bonus: place in PATH and use from the command line.
# Usage:
# find path -type f | xargs ruby highlight.rb
# gem contents metric_fu | grep lib | xargs ruby highlight.rb
# The highlighted code will be output to 'output.html' in the working directory
require 'coderay'
class Highlighter
def initialize
# import css classes from alpha style
@css = CodeRay::Styles::Alpha::CSS_MAIN_STYLES << "\n" << CodeRay::Styles::Alpha::TOKEN_COLORS
end
def highlight_file(filename)
text = File.binread(filename)
highlight(text)
end
def highlight(text)
CodeRay.scan(text, :ruby).div(css: :class, style: :alpha, line_numbers: :table, line_number_start: 0)
end
def highlight_files(filenames)
filenames.map do |filename|
"<br>#{filename}<br>" << highlight_file(filename)
end.join("\n<br>")
end
def write_html(inner_html, output_filename)
File.open(output_filename, 'w') do |output|
output.write "<html><head><style>#{@css}</style></head><body>"
output.write inner_html
output.write "</body></html>"
end
end
end
if $0 == __FILE__
hl = Highlighter.new
inner_html = hl.highlight_files(ARGV.to_a)
hl.write_html(inner_html, 'output.html')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment