I ma currently building an application using Ruby on Rails, and wanted to allow a user to create a “Note”. Since it will be simple notes, and do not need a full web editor with a lot of styling and option, I decided to use Markdown. So I wrote this small tutorial on using the Redcarpet gem to setup markdown within a Ruby on Rails project. Additionally, I included how to use another gem called Kramdown which does the same thing. Seems easier to include and some more features like PDF generation with Prawn, but according to the creators, Kramdown is “~150x slower than Redcarpet”.


Install Redcarpet and Rouge

gem 'redcarpet'
gem 'rouge'
bundle install

Create a Note

rails g resource Note title:string content:text show
rake db:migrate

Set up Redcarpet

# app/helpers/application_helper.rb

module ApplicationHelper

  require 'redcarpet'
  require 'rouge'
  require 'rouge/plugins/redcarpet'

  class HTML < Redcarpet::Render::HTML
    include Rouge::Plugins::Redcarpet
  end

  class HTMLWithPants < Redcarpet::Render::HTML
    include Redcarpet::Render::SmartyPants
  end

  def markdown(content)
    @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML, {
      autolink:            true,
      space_after_headers: true,
      fenced_code_blocks:  true,
      superscript:         true,
      underline:           true,
      highlight:           true,
      footnotes:           true,
      quote:               true,
      tables:              true
    })
    @markdown.render(content).html_safe
  end
end

Or, if you want to use Kramdown then add this instead

# app/helpers/application_helper.rb

module ApplicationHelper

  require 'kramdown'

  def markdown(content)
    Kramdown::Document.new(content).to_html.html_safe
  end

end

Finally, in the view file to render content

# app/views/notes/show.html.erb
<%= markdown(@note.content) %>

or

# app/views/notes/show.html.erb
<%= markdown @note.content %>

Sources:

  • https://github.com/vmg/redcarpet
  • https://github.com/jneen/rouge
  • https://github.com/gettalong/kramdown
  • http://kramdown.gettalong.org/tests.html

Related Post

Also read  What I learned after completing a Ruby on Rails project