Skip to content

Instantly share code, notes, and snippets.

@daveygm
Forked from sklppr/markdown2html.rb
Created December 5, 2013 18:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save daveygm/7810365 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "fileutils"
require "redcarpet"
OUTPUT_FOLDER = "html"
HTML_TEMPLATE = <<-HTML
<!DOCTYPE html>
<html>
<head>
<meta encoding="utf-8" />
<title>%s</title>
<style>
body { margin-top: 3em; }
.content { width: 33em; margin-left: 7em; margin-right: auto; }
</style>
</head>
<body>
%s
</body>
</html>
HTML
# Delete and recreate output folder.
FileUtils.rm_rf(OUTPUT_FOLDER)
Dir.mkdir(OUTPUT_FOLDER)
# Create Markdown to HTML converter.
converter = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
# Get all Markdown files in current folder and all subfolders.
Dir["**/*.markdown", "**/*.mdown", "**/*.md"].each do |file|
begin
# Construct output filename including original path.
input_file = File.path(file)
basename = File.basename(file, File.extname(file))
output_file = File.basename(File.path(file).gsub("/", "-"), File.extname(file)) + ".html"
# Convert Markdown to HTML.
puts "#{input_file} >> #{output_file}"
markdown = IO.read(file)
html = converter.render(markdown)
output = HTML_TEMPLATE % [basename, html]
# Write HTML to new file.
IO.write(File.join(OUTPUT_FOLDER, output_file), output)
rescue
puts $!.inspect, $@
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment