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)でもどっちでもいいのか?
- バッククオート+言語名でシンタックスハイライトになるが、コロン+ファイル名を付けるとエラーになる