7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsアプリにマークダウン&シンタックスハイライトを実装する

Last updated at Posted at 2016-03-06

railsアプリにマークダウンをhtml変換して表示&シンタックスハイライトでコードに色をつける機能の実装をする。

Gemfile

gem "redcarpet", "~> 2.3.0"
gem 'coderay'

追加してbundle install

helper

app/helpers/applecation_helper.rb
module ApplicationHelper
    require "redcarpet"
    require "coderay"

    class HTMLwithCoderay < Redcarpet::Render::HTML
        def block_code(code, language)
            case language.to_s
            when 'rb'
                lang = 'ruby'
            when 'yml'
                lang = 'yaml'
            when 'css'
                lang = 'css'
            when 'html'
                lang = 'html'
            when ''
                lang = 'md'
            else
                lang = language
            end

            CodeRay.scan(code, lang).div
        end
    end

    def markdown(text)
        html_render = HTMLwithCoderay.new(filter_html: true, hard_wrap: true)
        options = {
            autolink: true,
            space_after_headers: true,
            no_intra_emphasis: true,
            fenced_code_blocks: true,
            tables: true,
            hard_wrap: true,
            xhtml: true,
            lax_html_blocks: true,
            strikethrough: true
        }
        markdown = Redcarpet::Markdown.new(html_render, options)
        markdown.render(text)
    end
end

requireを忘れずに

view

app/views/articles/show.html.erb
<p><%= markdown(@article.content).html_safe %></p>

まとめ

  • html_safeはview側でもhelper側(markdown.render(text).html_safe)でもどっちでもいいのか?
  • バッククオート+言語名でシンタックスハイライトになるが、コロン+ファイル名を付けるとエラーになる
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?