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.
To install redcarpet gem go to your Gemfile and add:
# Gemfile gem "redcarpet"
then run the following command:
$ bundle install
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
$ rails db:migrate
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
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 %>
And congratulation you have added markdown to your application.