Sunday, December 01, 2013

Syntax Highlighting for Rails

1. Add rouge and redcarpet gems to Gemfile.

gem 'rouge'

gem 'redcarpet'

2. Install rouge gem.

$ bundle

3. Create initializer in config/initializers/rouge.rb
require 'rouge/plugins/redcarpet'

class CustomHtml < Redcarpet::Render::HTML
  include Rouge::Plugins::Redcarpet # yep, that's it.
end

4.  Use the HTML class as a renderer in markdown method in app/helper/application_helper.rb:

def markdown(text)
  render_options = {
    filter_html:     true,
    hard_wrap:       true, 
    link_attributes: { rel: 'nofollow' }
  }
  renderer = CustomHtml.new(render_options)

  extensions = {
    autolink:           true,
    fenced_code_blocks: true,
    lax_spacing:        true,
    no_intra_emphasis:  true,
    strikethrough:      true,
    superscript:        true
  }
  Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end

5.  For styling the output using Rouge built-in styles, create app/assets/stylesheets/rouge.css.erb with the following code:

<%= Rouge::Themes::ThankfulEyes.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Colorful.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Base16.render(:scope => '.highlight') %>

6. In your view app/views/articles/show.html.erb where you have markdown and code mixed, use the markdown helper:
 
  <%= markdown @article.content %>

References
2. You can even use it with RedCarpet

No comments:

Post a Comment