2
2

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 3 years have passed since last update.

Rails 「Markdown記法の導入について」

Posted at

#はじめに
標題の通り、作成しているアプリにMarkdown記法をできるようにしました。
何とか導入できましたので、復習も兼ねてoutput致します。
もうすでにご存知の方、省略の仕方等ご存知でしたら、ご教授願います。

#開発環境

  • ruby 2.6.3
  • Rails 5.2.4.1
  • macOS Catalina 10.15.3
  • VScode 1.42.1

#必要なGem

Gemfileに追記

gem 'redcarpet'

その後、bundle installです。

#redcarpetの機能を利用するための準備

  • app/helpers内に「markdown_helper.rb」ファイルを作成する。
  • markdown_helper.rb内に以下を記述する。
markdown_helper.rb
module MarkdownHelper
  def markdown(text)
    unless @markdown
      options = {
        hard_wrap: true
      }
      extensions = {
        no_intra_emphasis: true,
        tables: true,
        fenced_code_blocks: true,
        autolink: true,
        quote: true
      }
      renderer = Redcarpet::Render::HTML.new(options)
      @markdown = Redcarpet::Markdown.new(renderer, extensions)
    end
    @markdown.render(text).html_safe
  end
end

textに反映させるイメージで導入致しました。
htmlから変換できるようになっております。

#適用したいviewsフォルダ内へ追記

*〜*間は随時変更してください。

show.html.erb
 <span><div><%= markdown(@*comment.task.title*) %></div></span>

#結果

markdown1.png markdown2.png

##参考記事
勉強になりました。ありがとうございます。
@hkengo 様 https://qiita.com/hkengo/items/978ea1874cf7e07cdbfc
@shimoch 様 https://qiita.com/shimoch/items/466ed5cc5c232e58b34f
redcarpet公式README https://github.com/vmg/redcarpet

#さいごに
日々勉強中ですので、随時更新します。
皆様の復習にご活用頂けますと幸いです。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?