Redcarpet for Rails 4.0

The good thing about having something, even this simple blog, up and running is when something doesn't work the way you expect, you are inspired to figure out why and fix it. So, I'm happily blogging away and I realize in my DataTables, Bootstrap, JS and you post all of the code I typed in both looks like crap AND half of it is stripped out by Rails being smart.

Data in these views is rendered out by something simple like:

<%= simple_format @article.content %>

I wanted to keep simple_format and read around. I tried a number of tweaks to that. Things like chaining an, adding a raw to the start, played with pre tags and prettify and other stuff, considered gsub solutions and then went to the source at to see what there was. I tried:

<%= simple_format(@article.content, {}, sanitize: false %>

That nearly worked. But allowing the span stuff in those Java scripts in that blog caused my entire page to reformat and not do what I wanted. I kept poking around and came to Redcarpet as a possible solution.

As always I started at Railscasts and took a look at Unfortunately, that's quite old and the repository for Redcarpet has been entirely rewritten. So I was only able to use Ryan's work as a place to start. In poking around it seemed pretty straightforward. Here's how I got things to work.

First, add gem 'redcarpet' to your Gemfile, bundle and then restart your Rails server.

In my application_helper.rb I added the following method:

def markdown(content)
  @markdown ||=, autolink: true, space_after_headers: true, fenced_code_blocks: true)

I tried cleaning that up more by moving Redcarpet::Render::HTML to a method called "renderer" and the autolink, etc., part to "extensions" but that failed. I'll look at that later.

Anyway, the autolink means I can type webpages directly in as I'm typing here and it shows up. The space thing is just make it pretty I'm gathering. The fenced_code_blocks option allows code to be blocked off and protected by surrounding it with three ~~~ to start and ~~~ to end. Also, you can just indent four spaces and it marks it for you.

Then in my articles view I changed from:

<%= simple_format @article.content %>


<%= markdown(@article.content).html_safe %>

This combination and very simple change has cleaned up the text of the blogs and given me clean code blocks for examples. Hope that helps.

paperclip paperclip