Working With Markdown in Ruby

您所在的位置:网站首页 markdownp Working With Markdown in Ruby

Working With Markdown in Ruby

2023-03-23 11:53| 来源: 网络整理| 查看: 265

Imagine that you and your colleagues are working on a cool new project at work. Everyone's churning out code and firing on all cylinders, and everything seems to be going well, but then you remember that documentation also needs to get done for the project.

What do you choose? HTML could work, but it feels a bit clunky having to write all those tags. What about word processors or something like Google Docs? Well, these are fine, but for this project, you'd prefer something that's as close to your code as possible.

Thus, what should you use? A perfect (or near-perfect) documentation tool meets the following criteria:

Has simple syntax that most of your team can learn to use and thereby more easily contribute to the project's documentation. Is as close to your project's code base as possible. Is readable in raw or rendered format. Has a small file footprint. Is easily managed using git tooling. Can be rendered into popular publishing formats, such as HTML and PDF.

Markdown meets these criteria.

What Is Markdown?

Markdown is a simple markup language with the file extension `.md. It was created by John Gruber and Aaron Swartz in 2004 with the goal of making a format that was readable in its source-code form.

TL;DR

For the purposes of getting our project's documentation done, Markdown is perfect. In this article, you'll learn how to use two Ruby libraries to parse Markdown, and in a later section, we'll integrate one of the libraries with Sinatra to create a simple documentation app. You can clone the example app's source code from here.

Now let's get to it.

Parsing Markdown Using the Redcarpet Gem

Redcarpet is a Ruby library for processing Markdown. It's inbuilt renderers, one for outputting HTML and another for XHTML, are written in C, which makes it a very fast Markdown parser compared to other Ruby libraries.

Installing Redcarpet

If you have Ruby 1.9.2 or later, you can install the latest version (as of writing this article) of Redcarpet by running gem install redcarpet -v 3.3.4.

The heart of the library is its Redcarpet::Markdown class, which is used to parse the Markdown document you feed it and then use its attached renderer to do the HTML output.

It's recommended that you instantiate the Redcarpet::Markdown class once and then reuse it as needed.

Using Redcarpet

Initialize it as follows:

parser = Redcarpet::Markdown.new(renderer, extensions = {})

As you'll notice, the Redcarpet::Markdown class accepts two arguments; the first is the renderer you prefer (for the purposes of this tutorial, we'll default to the HTML renderer Redcarpet::Render::HTML), and the second argument is a hash of options.

Let's start with a simple example using the default renderer without specifying any options:

markdown_text =


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3