Using Markdown for Posts in a Rails Blog

  • rails, gems, tutorials
  • 1 Comment

Here is quick tutorial for a Rails blog that allows posts to be written in Markdown.

When I decided to rebuild my static blog website in Rails, I had trouble deciding how to build dynamic show pages for each blog post. Every blog post would have a different HTML structure and I just couldn't wrap my head around how this could work with Rails's templating system. Enter Markdown, the lightweight markup language created by John Gruber and Aaron Swartz, that easily converts to HTML.

Blog posts written in Markdown can be saved directly to the database, and Markdown allows each post to have its own unique combination of headline, paragraph, and link tags. When a Post show action is called, I can parse the Markdown and display it as HTML on the view. I am no longer restricted by the .ERB and HTML in my Posts view.

There are two awesome gems that make using Markdown in an app a breeze. The first is RedCarpet, a Ruby library for converting Markdown to HTML. The other is CodeRay, a gem that provides really cool looking syntax highlighting, a critical feature for any blog about programming.

Using the two gems together is quite simple. First, in app/Gemfile add:

gem 'redcarpet'
gem 'coderay'

Next, in app/helpers/application_helper.rb simply place the following code:

module ApplicationHelper
  class CodeRayify < Redcarpet::Render::HTML
    def block_code(code, language)
      CodeRay.scan(code, language).div
    end
  end

  def markdown(text)
    coderayified = CodeRayify.new(:filter_html => true, :hard_wrap => true)
      options = {
        :fenced_code_blocks => true,
        :no_intra_emphasis => true,
        :autolink => true,
        :strikethrough => true,
        :lax_html_blocks => true,
        :superscript => true
      }
    markdown_to_html = Redcarpet::Markdown.new(coderayified, options)
    markdown_to_html.render(text).html_safe
  end
end

RedCarpet has good documentation on the options hash that can be customized to fit your needs. CodeRay's documentation is thin, but one option that might come in handy is the ability to add line numbers to your code blocks by changing CodeRay.scan(code, language).div to CodeRay.scan(code, language).div(:line_numbers => :table).

All that's left is to parse the Markdown in the view and it's as simple as:

<%= markdown(@post.title) %>
<%= markdown(@post.text) %>

The Markdown content in the title and text fields in the database will now be converted to HTML in my view. For more information on Markdown syntax, check out Daring Fireball or Github.