Adding Markdown to your Rails application

ashawareb

Abd ElRahman Shawareb

Posted on June 8, 2021

Adding Markdown to your Rails application

In this guide I will show you how to add markdown to your rails application. We will use redcarpet gem and I assume that you have created your rails application that we will work on.

Install redcarpet

To install redcarpet gem go to your Gemfile and add:

# Gemfile 
gem "redcarpet"
Enter fullscreen mode Exit fullscreen mode

then run the following command:

$ bundle install
Enter fullscreen mode Exit fullscreen mode

Generating a resource

After we successfully installed our gem, we need a recourse to work with and test our work, so we will create Post scaffold to work with.

To create the Post scaffold run the following commands:

$ rails generate scaffold Post title:string body:text
Enter fullscreen mode Exit fullscreen mode
$ rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Extracting logic to a helper

After we successfully installed redcarpet gem and created our scaffold it's the time to add markdown to our application.

In order to be DRY (don't repeat yourself) we will create a helper method to use whenever we want to add markdown. So in our application_helper.rb we will add the following code:

def markdown(text)
    options = %i[
      hard_wrap autolink no_intra_emphasis tables fenced_code_blocks
      disable_indented_code_blocks strikethrough lax_spacing space_after_headers
      quote footnotes highlight underline
    ]
    Markdown.new(text, *options).to_html.html_safe
  end
Enter fullscreen mode Exit fullscreen mode

This method titled markdown will take a text as an argument and will be the output of Post body field. Notice the options variable defined with an array of settings you can pass to Redcarpet. These dictate what you do and don't want when it comes to rendering markdown within your app.

Now let's use this helper in our views

<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Body:</strong>
  <%= markdown(@post.body) %>
</p>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Enter fullscreen mode Exit fullscreen mode

And congratulation you have added markdown to your application.

💖 💪 🙅 🚩
ashawareb
Abd ElRahman Shawareb

Posted on June 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related