Markdown views with syntax highlighting in Rails

programming Ruby ruby Ruby on Rails ruby-on-rails Markdown markdown syntax-highlighting

Today I had to add technical documentation pages to a Rails app. I chose to write those in Markdown as that’s what I’m used to and it’s a widely-used format. This post describes how to render Markdown views in a Ruby on Rails application with Pygments for code syntax highlighting.

The markdown-rails gem enables .html.md views. Redcarpet is a better parser which you’ll want to use to have features like GitHub Flavored Markdown. Finally, pyments.rb will handle the syntax highlighting.

Add those gems to your Gemfile and run bundle install:

gem "markdown-rails"
gem "redcarpet"
gem "pygments.rb"

To configure the parser and enable syntax highlighting, you can add this initializer:

# File: config/initializers/markdown.rb

# Override the default renderer to add syntax
# highlighting with Pygments.
class PygmentsHTML < Redcarpet::Render::HTML
  def block_code code, language
    Pygments.highlight code, :lexer => language
  end
end

MarkdownRails.configure do |config|
  # See https://github.com/vmg/redcarpet for options.
  markdown = Redcarpet::Markdown.new(PygmentsHTML,
    :tables => true,
    :fenced_code_blocks => true,
    :autolink => true
  )

  config.render do |markdown_source|
    markdown.render markdown_source
  end
end

Note that you must have Pygments’ pygmentize command installed and in your path. You may install it on most platforms with easy_install:

easy_install Pygments

Well, that was pretty painless.