RailsでさくっとMarkdown対応する方法を紹介します。
マークダウン形式で書かれたテキストをHTMLに変換する機能を提供するgemが大きく2つあります。
- redcarpet ★4222
- commonmarker ★137
(★は2018/05/31時点)
redcarpetは僕も以前から使っていて、オプションが豊富でがんばればいろんなことができる、大きめのライブラリという印象です。(GitHubでも使われてるんでしたっけ?適当なこと言ったらいけないか)
で、もう一個のcommonmarkerはCommonMarkというMarkdownに対応するためのライブラリです。あるプロジェクトでredcarpetで3重にネストした箇条書きを上手く処理できなくて困ってたところに、コレに出会ってうまくいったのでこっちを採用しています。
CommonMarkは仕様を明確にしたMarkdownという感じの存在です。
redcarpet gemのコードを書いている人も参加しているみたい。
Redcarpet was written by Vicent Martí.
のところ、および、CommonMarkのサイトの Who are you?のところの
Vicent Marti, vicent@github.com
が同一人物のようですね。
example
凝ったことをやらないのであればcommonmarkerでサクッと作ってもいいのでは?と思い最小限のRailsのサンプルを紹介します。
commonmarker gemのREADMEの冒頭部分を例としてHTMLにしてみます。
commonmarker/README.md at master · gjtorikian/commonmarker
1# CommonMarker
2
3[](https://travis-ci.org/gjtorikian/commonmarker) [](http://badge.fury.io/rb/commonmarker)
4
5Ruby wrapper for [libcmark-gfm](https://github.com/github/cmark),
6GitHub's fork of the reference parser for CommonMark. It passes all of the C tests, and is therefore spec-complete. It also includes extensions to the CommonMark spec as documented in the [GitHub Flavored Markdown spec](http://github.github.com/gfm/), such as support for tables, strikethroughs, and autolinking.
7
8For more information on available extensions, see [the documentation below](#extensions).
9
10## Installation
11
12Add this line to your application's Gemfile:
13
14 gem 'commonmarker'
15
16And then execute:
17
18 $ bundle
19
20Or install it yourself as:
21
22 $ gem install commonmarker
23
24## Usage
25
26### Converting to HTML
27
28Call `render_html` on a string to convert it to HTML:
導入は↑に書いてあるとおり、Gemfileに書いてbundle install だけでOKです。ビューで毎度commonmarkerを呼ぶのは面倒なので、僕は大体ヘルパーにしておいて使います。
1module ApplicationHelper
2 def md2html(text)
3 html = CommonMarker.render_html(text)
4 raw(html)
5 end
6end
あとはビューでこのヘルパーのメソッドにMarkdown形式のテキストを入れるだけです。
<% text = "#{↑のマークダウン}" %>
<%= md2html(text) %>
レンダリング結果が↓です。いい感じです。