Skip to content

Instantly share code, notes, and snippets.

@mahm
Created April 21, 2017 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahm/5a677285e8b933bb3f60c7ebff3a5596 to your computer and use it in GitHub Desktop.
Save mahm/5a677285e8b933bb3f60c7ebff3a5596 to your computer and use it in GitHub Desktop.
module Kramdownable
extend ActiveSupport::Concern
include ActionView::Helpers::TextHelper
def autolink_filter(content)
auto_link(content, html: {target: '_blank'}, sanitize: false)
end
def kramdown
Kramdown::Document.new(body || '', kramdown_options)
end
def kramdown_options
{
auto_id_prefix: 'toc-',
auto_ids: true,
input: 'GFM',
coderay_line_numbers: nil
}
end
def headers
kramdown.root.children.select { |el| el.type == :header }
end
# h2だけ右下のtocとして出力する
def headers_for_toc
(0...headers.size).map do |number|
toc_id = "#{kramdown_options[:auto_id_prefix]}section"
toc_id += "-#{number}" if number > 0
if headers[number].options[:level] == 2
{ toc_id: toc_id, value: headers[number].options[:raw_text] }
else
nil
end
end.compact
end
def to_html
autolink_filter(kramdown.to_html)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment