Post

Markdown in Ruby on Rails with RedCarpet

What is Markdown

Markdown is a markup language, created by John Gruber and Aaron Swartz, that allows you to easily format text by using special characters in a text document. When processed, the markdown characters are converted into formatted text. If you wanted to make a particular word or sentence have a bold font weight, you can wrap it in asterisks.

  • Input: I want to bold this word: **Bingo**
  • Output: I want to bold this word: Bingo

You can find markdown cheat sheets everywhere, but one that I found helpful was from markdownguide.org.

Ruby Gem: redcarpet

I was first introduced to the redcarpet gem by Andy Leverenz’s YouTube channel, Web-Crunch. This gem allows you to render HTML from the markdown in a text field in your application. It’s not limited to text fields or text areas. You can add text to parts of your page and then call the render method on that text to format it as HTML.

I originally started looking for markdown gems to use in my Rails projects because I wasn’t thrilled with the Trix editor included with ActionText. This gem fit the bill!

Rails App with RedCarpet gem

Create the app

First create a new rails app by running the rails new generator and then cd into your newly created app. Since this is just a barebones test app, we won’t do much customization. If you decide to use Tailwind CSS, you’ll need to set the styles for all HTML elements since the standard CSS styles that we are used to seeing are removed. This app uses standard css and html formats, so H1 tags look like the H1 tags you are used to seeing.

Note: I’m using Rails 7.0.2.3 and Ruby 3.0.2

1
2
rails new markdown_app
cd markdown_app

Next we’ll create a simple post scaffold that has a title and content fields and run the migration.

1
2
3
4
rails g scaffold Post title:string content:text

# Run the migration.
rails db:migrate

Next, we’ll set the root path in the routes.rb file.

1
2
3
4
Rails.application.routes.draw do
  resources :posts
  root "posts#index"
end

Start the rails server and open a web browser to http://localhost:3000

rails s

Your test app should load to the Posts index page and should look like this:

Safari browser showing Post page

Safari browser showing Post page

Create a test post

Click on the New post link, enter a title and some text into the content field, and click Create Post. Below is some example text you can copy and paste. Most of this text was generated with the Hipster Ipsum generator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Heading 1

## Heading 2

### Heading 3

==I'm baby== <b>deep</b> v plaid copper mug literally iceland, flannel slow-carb la croix helvetica hot chicken food truck 8-bit subway tile before they sold out. Franzen direct trade yr, lomo bushwick helvetica truffaut put a bird on it. Helvetica selvage af single-origin coffee. VHS lomo enamel pin, synth glossier mixtape hammock waistcoat microdosing chartreuse cold-pressed. Drinking vinegar marfa retro, meh banjo tousled ugh.

```ruby
module ApplicationHelper

  def markdown(text)
    options = [:hard_wrap, :autolink, :no_intra_emphasis, :fenced_code_blocks, :underline, :highlight, :no_images, :filter_html, :safe_links_only, :prettify, :no_styles]
    Markdown.new(text, *options).to_html.html_safe
  end
end
```

_Edison bulb offal iPhone keffiyeh, DIY heirloom taiyaki poke lo-fi sriracha selvage._ Next level man braid succulents church-key sriracha VHS tofu narwhal scenester raw denim letterpress.

We can put some ==`inline code`== here with some highlighting applied to it.

**XOXO** typewriter vegan man braid. Post-ironic vice tote bag, disrupt PBR&B banjo tumeric next level drinking vinegar ramps copper mug trust fund taiyaki narwhal pour-over. Poutine farm-to-table selvage chia raclette kickstarter. Austin occupy vaporware beard copper mug disrupt, cred readymade unicorn _vegan_.

1. This thing
2. This other thing
3. This other other thing

Link: http://www.mitchcraver.com this will automatically format the link for us once the redcarpet gem is installed and configured.

> block quote of some kind goes here!

When you are done, it should look something like this. Watch your eyes–it is very ugly!

webpage showing pasted text that it unformatted.

Add and configure the gem

In your terminal run bundle add redcarpet. This command will add the redcarpet gem to your gemfile.rb and install the gem for your app.

The first thing we need to do is edit the application_helper.rb file to add a method to process text that we feed it. It will spit out the formatted HTML from our text.

1
2
3
4
5
6
7
8
9
module ApplicationHelper

  def markdown(text)
    options = [:hard_wrap, :autolink, :no_intra_emphasis, :fenced_code_blocks, :underline, :highlight,
    :no_images, :filter_html, :safe_links_only, :prettify, :no_styles]
    Markdown.new(text, \*options).to_html.html_safe
  end

end

Here we configured a method called markdown that takes one parameter called text. Inside of this method we define a variable called options that lists different symbols that tells the redcarpet gem what to process and what to ignore. You can find a list of all options on the redcarpet GitHub page.

Finally, the Markdown.new(text, \*options).to_html.html_safe part tells the Markdown method (part of the Redcarpet class) to process the text we pass in using the options we defined.

Now that we have the helper file ready to go, we can add a bit of code to the views to render the HTML from the markdown we included in the code.

In Rails 7, the scaffold uses partials to render the post we created. Your file tree should look something like this:

markdown app file tree in VSCode

Open the \_post.html.erb file and add the markdown method around content field in the erb tag.

1
2
3
4
5
6
7
8
9
10
<div id="<%= dom_id post %>">
  <p>
    <strong>Title:</strong>
    <%= post.title %>
  </p>
  <p>
    <strong>Content:</strong>
    <%= markdown(post.content) %>
  </p>
</div>

That’s it. If you go to the root of your app (http://localhost:3000) or the show page for the post you created, you should see the magic that the redcarpet gem provides.

markdown formatted properly

Conclusion

Pat yourself on the back! You created a new rails app, installed the redcarpet gem, configured a helper with options for the redcarpet gem, and modified the views to enable the markdown method to format the text with very little effort!

This post is licensed under CC BY 4.0 by the author.