require 'pry' require 'redcarpet' class Generate < Thor include Thor::Actions desc "index", "generate index.html from README.md" def index puts "Processing README.md to generate a new index.html..." relative_path_to_readme = "README.md" relative_path_to_index = "index.html" # `r` means we're using the "read" mode with the file # we need a String for Redcarpet, it doesn't accept File objects. string = File.open(relative_path_to_readme, 'r') { |file| file.read } renderer = HTMLwithHeaderLinks.new markdown = ::Redcarpet::Markdown.new(renderer, markdown_renderer_options) rendered_markdown = markdown.render(string) html_output = template { rendered_markdown } File.open(relative_path_to_index, 'w') { |file| file.write(html_output) } puts "All done!" end private def template(&block) <<-HTML.gsub /^\s+/, "" Keep a Changelog
#{yield}
HTML end def markdown_renderer_options { autolink: true, no_intra_emphasis: true, fenced_code_blocks: true, disable_indented_code_blocks: true, lax_spacing: true, lax_html_blocks: true, strikethrough: true, superscript: true, tables: true, with_toc_data: true } end end class HTMLwithHeaderLinks < Redcarpet::Render::HTML def header(title, level) @headers ||= [] permalink = title.gsub(/\W+/, '-').downcase if @headers.include?(permalink) permalink += '_1' permalink = permalink.succ while @headers.include?(permalink) end @headers << permalink %( #{title} ) end end