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)