近&況

Recent Posts
Edit

Adding code highlight to your Sinatra app with Rouge

2016-10-25

Rouge is a syntax highlighting library for Ruby. I've added syntax highlight to this blog, so here's how.

Install

Add gem "rouge" to your Gemfile.

require 'rouge'

Redcarpet

I use redcarpet gem to render markdown document. Rouge has out-of-box support of redcarpet, so no other gems are needed.

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

...

class Post < ActiveRecord::Base
  class HtmlWithRouge < Redcarpet::Render::HTML
    include Rouge::Plugins::Redcarpet
  end
  def rendered_body
    markdown = Redcarpet::Markdown.new(HtmlWithRouge,
      no_intra_emphasis: true,
      tables: true,
      fenced_code_blocks: true,
      autolink: true,
      strikethrough: true,
      footnotes: true,
    )
    return markdown.render(self.body)
  end
end

With this settings, Post#rendered_body will return a html snippet like this:

<pre class="highlight ruby"><code><span class="nb">print</span> <span class="mi">123</span>
</code></pre>

You see some attributes like class="nb" or class="mi" added by Rouge. Now we need a CSS to highlight them.

CSS

First, add a link into the <head> tag (usually lies in the layout file).

<head>
  <link rel="stylesheet" href="/highlight.css" type="text/css" />

Then modify your Sinatra app to serve the css.

  get '/highlight.css' do
    headers 'Content-Type' => 'text/css'
    Rouge::Themes::Base16.mode(:light).render(scope: '.highlight')
  end

(Alternatively, you can save the output into public/highlight.css and serve them statically. This may improve the loading time of your website when it has huge traffic.)

Now you should see the code blocks in the markdown highlighted on your Sinatra app :-)

Themes

There are some more themes in the rouge gem. You can use these thems like this.

  Rouge::Themes::Github.render(scope: '.highlight')