Markdown ASTs with Commonmarker

    For converting Markdown, Rubyists may default to Redcarpet or Kramdown. I suggest taking a look at Commonmarker, a Ruby gem built on top of comrak, a Rust of implementation the GitHub-flavored version of the CommonMark spec.

    Why? One reason is you can parse Markdown into an abstract syntax tree (AST) which enables powerful customization of what you can do with the markdown source.

    require 'commonmarker'
    Commonmarker.to_html('"Hi *there*"', options: {
        parse: { smart: true }
    })
    # => <p>“Hi <em>there</em>”</p>\n
    
    doc = Commonmarker.parse("*Hello* world", options: {
        parse: { smart: true }
    })
    doc.walk do |node|
      puts node.type # => [:document, :paragraph, :emph, :text, :text]
    end

    Back to snippets