カスタムMarkdown機能を実装する方法
gemを使って簡単にmarkdown機能を実装していきます。
まずはgemfileに2つのgemを追加
markdownのgem redcarpet | RubyGems.org | your community gem host
シンタックスハイライトのgem coderay | RubyGems.org | your community gem host
Gemfile gem 'redcarpet', '~> 3.3', '>= 3.3.4' gem 'coderay', '~> 1.1'
app/helpers/application_helper.rbにメソッドを書いていきます。(コピペで大丈夫)
module ApplicationHelper class CodeRayify < Redcarpet::Render::HTML def block_code(code, language) CodeRay.scan(code, language).div(:line_numbers => :table) end end def markdown(text) coderayified = CodeRayify.new(:filter_html => true, :hard_wrap => true) options = { :fenced_code_blocks => true, #ここのoptionは任意で好きなようにカスタマイズしてok :no_intra_emphasis => true, :autolink => true, :strikethrough => true, :lax_html_blocks => true, :superscript => true } markdown_to_html = Redcarpet::Markdown.new(coderayified, options) markdown_to_html.render(text).html_safe end end
viewのmarkdownにしたいところでメソッドを呼ぶだけ
app/views/tasks/show.html.erb
<%= markdown(@task.note) %>
ここまでで実装は終了です。 フォームのtext_field内で実際に試してみましょう。
viewの画面で確認
できたああああああ
なお ActionView::Template::Error (Symbol or String expected, but NilClass given.のエラーが途中出てきた場合は Block code starting with 4 spaces cannot be rendered when used with CodeRayify · Issue #308 · vmg/redcarpet · GitHub ここを参考にしてみてください。