LoginSignup
1
0

More than 5 years have passed since last update.

kramdown を使って Markdown を AST に変換する

Last updated at Posted at 2017-10-10

kramdown を使用することで Markdown を AST に変換することが出来ます。

require "pp"
require "kramdown"

code =<<-MKD
# title

hello world

- list1
- list2
MKD

doc = Kramdown::Document.new(code, input: "GFM")
result = doc.to_hash_ast

pp result

出力結果

{:type=>:root,
 :options=>
  {:encoding=>#<Encoding:UTF-8>,
   :location=>1,
   :options=>{},
   :abbrev_defs=>{},
   :abbrev_attr=>{}},
 :children=>
  [{:type=>:header,
    :attr=>{"id"=>"title"},
    :options=>{:level=>1, :raw_text=>"title", :location=>1},
    :children=>[{:type=>:text, :value=>"title", :options=>{:location=>1}}]},
   {:type=>:blank, :value=>"\n"},
   {:type=>:p,
    :options=>{:location=>3},
    :children=>
     [{:type=>:text, :value=>"hello world", :options=>{:location=>3}}]},
   {:type=>:blank, :value=>"\n"},
   {:type=>:ul,
    :options=>{:location=>5},
    :children=>
     [{:type=>:li,
       :options=>{:location=>5},
       :children=>
        [{:type=>:p,
          :options=>{:location=>5, :transparent=>true},
          :children=>
           [{:type=>:text, :value=>"list1", :options=>{:location=>5}}]}]},
      {:type=>:li,
       :options=>{:location=>6},
       :children=>
        [{:type=>:p,
          :options=>{:location=>6, :transparent=>true},
          :children=>
           [{:type=>:text, :value=>"list2", :options=>{:location=>6}}]}]}]}]}

kramdown のバージョンが 1.14.0 未満の場合は #to_hash_ast が使用できないので下記のコードを使用します。(kramdown issue#435)

- result = doc.to_hash_ast
+ result, warnings = Kramdown::Converter::HashAST.convert(doc.root, doc.options)
1
0
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
1
0