-
-
Save samsonjs/7801881 to your computer and use it in GitHub Desktop.
A slightly more idiomatic version of Brent Simmon's program to convert a folder of Markdown files to HTML.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# PBS 4 Dec. 2013 | |
# Renders HTML for all the .markdown files in the current directory. | |
# Gives each file a .html suffix. | |
# Saves them in a subfolder called HTML. | |
require 'rdiscount' | |
require 'find' | |
require 'fileutils' | |
def markdown_file?(f) | |
filename = File.basename(f) | |
if filename[0] == ?. | |
false | |
elsif FileTest.directory?(f) | |
false | |
else | |
extension = File.extname(filename) | |
extension == '.markdown' | |
end | |
end | |
def filename_with_suffix_dropped(filename) | |
filename.sub(/\.[^.]*$/, '') | |
end | |
def filename_with_suffix_changed(filename, new_suffix) | |
filename = filename_with_suffix_dropped(filename) | |
filename + new_suffix | |
end | |
def write_file(s, f) | |
FileUtils.mkdir_p(File.dirname(f)) | |
f = File.open(f, 'w') do |f| | |
f.puts(s) | |
end | |
end | |
def html_text_for_file(f) | |
markdown_text = File.read(f) | |
html_text = RDiscount.new(markdown_text).to_html | |
filename = File.basename(f) | |
title = filename_with_suffix_dropped(filename) | |
style = "<style>body {margin-top: 3em;}\n.content {width: 33em; margin-left: 7em; margin-right: auto}</style>\n" | |
file_text = "<html>\n<head><title>#{title}</title>#{style}</head></body><div class=content>#{html_text}</div></body></html>" | |
file_text | |
end | |
def generate_and_write_html(f) | |
filename = File.basename(f) | |
html_filename = filename_with_suffix_changed(filename, '.html') | |
folder = File.dirname(f) | |
html_filepath = File.join(folder, 'html', html_filename) | |
html_text = html_text_for_file(f) | |
write_file(html_text, html_filepath) | |
end | |
folder = Dir.pwd | |
Find.find(folder) do |f| | |
filename = File.basename(f) | |
if markdown_file?(f) | |
puts(filename) | |
generate_and_write_html(f) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment