Skip to content

Instantly share code, notes, and snippets.

@suan
Forked from courtenay/STDOUT
Last active December 17, 2015 23:58
Show Gist options
  • Save suan/5692767 to your computer and use it in GitHub Desktop.
Save suan/5692767 to your computer and use it in GitHub Desktop.
require 'redcarpet'
require 'rexml/document'
module Redcarpet::Render
class Custom < Base
def header(title, level)
@headers ||= []
title_elements = REXML::Document.new(title)
flattened_title = title_elements.inject('') do |flattened, element|
flattened += if element.respond_to?(:text)
element.text
else
element.to_s
end
end
permalink = flattened_title.downcase.gsub(/[^a-z\s]/, '').gsub(/\W+/, "-")
# for extra credit: implement this as its own method
if @headers.include?(permalink)
permalink += "_1"
# my brain hurts
loop do
break if [email protected]?(permalink)
# generate titles like foo-bar_1, foo-bar_2
permalink.gsub!(/\_(\d+)$/, "_#{$1.to_i + 1}")
end
end
@headers << permalink
%(\n<h#{level}><a name="#{permalink}" class="anchor" href="##{permalink}"><span class="anchor-icon"></span></a>#{title}</h#{level}>\n)
end
end
end
# output
> gh = Redcarpet::Render::GithubStyleTitles.new
> puts Redcarpet::Markdown.new(gh).render "test\n\n# test 1\n\n# test 2\n\n# test 1\n\n# test 1"
=>
<a name="test-1" class="anchor" href="#test-1"><span class="anchor-icon"></span></a><h1 id="test-1">test 1</h1>
<a name="test-2" class="anchor" href="#test-2"><span class="anchor-icon"></span></a><h1 id="test-2">test 2</h1>
<a name="test-1_1" class="anchor" href="#test-1_1"><span class="anchor-icon"></span></a><h1 id="test-1_1">test 1</h1>
<a name="test-1_2" class="anchor" href="#test-1_2"><span class="anchor-icon"></span></a><h1 id="test-1_2">test 1</h1>
@rafabene
Copy link

Excellent!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment