Monday, September 26, 2016

Code Snippets Rails 5 App

1. Add the rouge and redcarpet gems to Gemfile.

gem 'rouge'
gem 'redcarpet'

Run bundle.

2. Create the snippet resource.

rails g scaffold snippet code:text

3. Create a config/initializers/route.rb:

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

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

4. Define a markdown helper for the view in the application helper.

module ApplicationHelper
  def markdown(text)
    render_options = {
      filter_html:     true,
      hard_wrap:       true, 
      link_attributes: { rel: 'nofollow' }
    renderer =

    extensions = {
            line_format: true,
      autolink:           true,
      fenced_code_blocks: true,
      lax_spacing:        true,
      no_intra_emphasis:  true,
      strikethrough:      true,
      superscript:        true
    }, extensions).render(text).html_safe

5. Create rouge.css.erb in app/stylesheets folder:

<%= Rouge::Themes::Github.render(:scope => '.highlight') %>

6. Change the size of text area in the form partial.

class="field"> <%= f.label :code %> <%= f.text_area :code, cols: 100, rows: 40 %>

7. Use the markdown helper we created in the view snippet page show.html.erb:

  <%= markdown(@snippet.code.html_safe) %>

8. You can download the source for this article from high.

No comments:

Post a Comment