Upgrading to Redcarpet v2.0 with highlighting of code blocks with Albino/Pygments


Here's how:

module ApplicationHelper
  def markdown(text, *renderer)      
    case renderer[0]
    when :authored
      rndr = HTMLwithAlbino.new(:hard_wrap => true, :gh_blockcode => true, 
          :filter_html => false, :safe_links_only => true)
    when :featured
      rndr = HTMLwithAlbino.new(:hard_wrap => true, :gh_blockcode => true, 
          :filter_html => true, :safe_links_only => true)
    else
      rndr = HTMLwithAlbino.new(:hard_wrap => true, :gh_blockcode => true, 
          :filter_html => true, :no_images => true, :no_styles => true,
          :safe_links_only => true)
    end
    redcarpet = Redcarpet::Markdown.new(rndr, :space_after_headers => true,
      :fenced_code_blocks => true, :autolink => true, :no_intra_emphasis => true,
      :strikethrough => true, :superscripts => true)
    redcarpet.render(text).html_safe
  end

end

# create a custom renderer that allows highlighting of code blocks
class HTMLwithAlbino < Redcarpet::Render::HTML      
  def block_code(code, language)
    Albino.colorize(code, language)
  end
end

Calling markdown without any arguments will assume publicly created content, hence, it filters out as much as possible; still doing Albino.colorize() instead of Albino.safe_colorize() as I haven't upgraded it yet.

39504_423693505681_805695681_4704763_2511381_n_normal
Nico 2011-12-13 13:04:01

I would personally prefer a more DRY version, where the HTMLwithAlbino instance is created only once, since only the properties hash is changing:

https://gist.github.com/1472055


Mike_normal
Michael de Silva 2011-12-13 13:24:01

Thanks Nico! I've gone with

   def markdown(text, *renderer)      
    rndr_flags = { 
      hard_wrap:       true,
      gh_blockcode:    true,
      safe_links_only: true,
      filter_html:     true
    }
    case renderer[0]
    when :authored
      rndr_flags[:filter_html] = false
    else
      rndr_flags.merge({:no_images => true, :no_styles => true})
    end
    rndr = HTMLwithAlbino.new(rndr_flags)
    redcarpet = Redcarpet::Markdown.new(rndr, :space_after_headers => true,
      :fenced_code_blocks => true, :autolink => true, :no_intra_emphasis => true,
      :strikethrough => true, :superscripts => true)
    redcarpet.render(text).html_safe
  end

You need to sign in, either via Twitter or Facebook to post a comment.