Markdown is a fantastic way to format documents. It provides a simple and clear syntax that can be used to mark up everything from blogs to user comments. In this article we will use the Redcarpet gem to render markdown in our Rails application.

Rails Application Setup

The first thing we need to do is add the Redcarpet gem to our gemfile. Open up your gemfile and add the following line.

Gemfile:

gem 'redcarpet', '~> 3.0.0'

Now run a bundle install to install it.

Terminal Commands:

bundle install

For the sample app we will build a very simple blog. To do this we will need to create both a model and a controller. The model, post, will store the blog post information. It will contain three attributes. The first attribute, title, is the title of the post. The second attribute, body, contains the actual body of the post, the final attribute, published at, is the publish date of the post. The controller for Posts will have 2 methods, index and show. Run the commands below to create the model and the controller now.

Terminal Commands:

rails g resource Post title:string body:text published_at:datetime -a index show
rake db:migrate

Next we need to make a couple modifications to our routes file. We need to remove a redundant set of actions and set a home page. Open up your routes file and modify it so that it looks like the code listed below. Be sure not to overwrite the first line that contains your application's name.

config/routes.rb:

MarkdownExample::Application.routes.draw do
  resources :posts, only: [:index, :show]
  root to: "posts#index"
end

Excellent, now let's add some seed data to work with. Open your seeds file and add in the code listed below. This code will create a couple of posts that we can use for example purposes.

db/seeds.rb:

Post.delete_all

Post.create(
  id: 1,
  title: "My Very First Post",
  published_at: Time.now - 1.day,
  body: 
  %Q{### There Is Something You Should Know!

  This is my very first post using markdown!

  How do you like it?  I learned this from [RichOnRails.com](http://richonrails.com/articles/rendering-markdown-with-redcarpet)!}
)

Post.create(
  id: 2,
  title: "My Second Post",
  published_at: Time.now,
  body: 
  %Q{### My List of Things To Do!

  Here is the list of things I wish to do!
  
  * write more posts
  * write even more posts
  * write even more posts!}
)

Now run a rake db:seed to seed the database.

Terminal Commands:

rake db:seed

Great! Now we need to create a helper method. This helper method will allow us to quickly and easily set up Redcarpet with some default options and then render the markdown passed in. Open up your application helper file and add in the code listed below.

app/helpers/application_helper.rb:

module ApplicationHelper
  def markdown(text)
    options = {
      filter_html:     true,
      hard_wrap:       true, 
      link_attributes: { rel: 'nofollow', target: "_blank" },
      space_after_headers: true, 
      fenced_code_blocks: true
    }

    extensions = {
      autolink:           true,
      superscript:        true,
      disable_indented_code_blocks: true
    }

    renderer = Redcarpet::Render::HTML.new(options)
    markdown = Redcarpet::Markdown.new(renderer, extensions)

    markdown.render(text).html_safe
  end
end

Great! Now lets modify our controller. Open up your posts controller and modify it so that it looks like the code listed below.

app/controllers/posts_controller.rb:

class PostsController < ApplicationController
  def index
    @posts = Post.order("published_at DESC")
  end

  def show
    @post = Post.find(params[:id])
  end
end

Now lets add some code to our views. Open up the index view for posts and add in the code listed below.

app/views/posts/index.html.erb:

<h1>My Blog</h1>
<hr />
<% @posts.each do |post| %>
  <h1><%= link_to post.title, post %></h1>
  
  <p>
    <%= markdown(post.body) %>
  </p>
  <h5>Published <%= time_ago_in_words post.published_at %> ago</h5>

  <% if post != @posts.last %>
  <hr />
  <% end %>
<% end %>

Finally lets add some code for the show view.

app/views/posts/show.html.erb:

<h1><%= @post.title %></h1>
<hr />
  
<p>
  <%= markdown(@post.body) %>
</p>
<h4>Published <%= time_ago_in_words @post.published_at %> ago</h4>
<%= link_to "Back to Index", posts_path %>
That's it! That's all there is to it! if you fire up your rails server and visit http://localhost:3000 you'll see the markdown has been rendered. For a complete reference to redcarpet, see the Redcarpet Github page. Thanks for reading!