3. Using the Ruby API
In addition to the command line interface, Asciidoctor provides a Ruby API. The API is intended for integration with other software projects and is suitable for server-side applications, such as Rails, Sinatra and GitHub.
Asciidoctor also has a Java API that mirrors the Ruby API. The Java API calls through to the Ruby API using an embedded JRuby runtime. See the AsciidoctorJ project for more information.
To use Asciidoctor in your application, you first need to require the gem:
require 'asciidoctor'
This statement makes all of the public APIs in Asciidoctor available to your script or application. You are now ready to start processing AsciiDoc documents.
The main entry points in the Asciidoctor API are the static methods to load or convert AsciiDoc documents, which we’ll cover the next two chapters.
To parse a file into an Asciidoctor::Document object:
doc = Asciidoctor.load_file 'mysample.adoc'
You can get information about the document:
puts doc.doctitle
puts doc.attributes
More than likely, you will want to convert the document. To convert a file containing AsciiDoc markup to HTML 5, use:
Asciidoctor.convert_file 'mysample.adoc'
The command will output to the file mysample.html in the same directory.
You can convert the file to DocBook 5.0 by setting the :backend option to 'docbook':
Asciidoctor.convert_file 'mysample.adoc', backend: 'docbook'
The command will output to the file mysample.xml in the same directory. If you’re on Linux, you can view the file using Yelp.
You can also use the API to convert strings and load custom templates.