Rails on Rouge - Ultimate Syntax Highlighting Guide
We developers love syntax/code highlighting, don't we. Let it be our IDE like VisiualStudio, a text editor like VSCode or a terminal editor like VIM is nothing without a good syntax highlighter. It is also very important that we be able to select a theme that reflects our personality. Why should our blogs be any different?
This is how I have setup Rouge on my Ruby on Rails projects. It is easy and its nice!
Implementation
Lets install gems and bundle install
.
# Gemfile
gem 'redcarpet'
gem 'rouge'
The following class, Markdown
, will have the responsibility to convert the markdown to HTML and also process the code. My system
folder is having any code that doesn't belong in either helpers, models or controllers.
# frozen_string_literal: true
# app/system/markdown.rb
require 'redcarpet'
require 'rouge'
require 'rouge/plugins/redcarpet'
# Markdown
class Markdown
class HTML < Redcarpet::Render::HTML
include Rouge::Plugins::Redcarpet
end
EXTENSIONS = {
autolink: true,
hightlight: true,
superscript: true,
fenced_code_blocks: true,
no_intra_emphasis: true,
lax_spacing: true,
strikethrough: true,
tables: true
}
OPTIONS = {
filter_html: true,
hard_wrap: true,
link_attributes: { rel: 'nofollow', target: '_blank' }
}
attr_reader :markdown
def initialize
@renderer = HTML.new(OPTIONS)
@markdown = Redcarpet::Markdown.new(
@renderer,
EXTENSIONS
)
end
def render(text = nil)
markdown.render(text)
end
end
Next we would need to implement a helper method to utilise the new Markdown
class we wrote.
# frozen_string_literal: true
# app/helpers/application_helper.rb
module ApplicationHelper
def markdown(text = nil)
@markdown ||= Markdown.new
raw @markdown.render(text).html_safe
end
end
Finally we need to use it in our pages. For example
// app/views/blogs/show.html.slim
= markdown @blog_post.body
I hope it was helpful. Have a nice day!
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.