Saturday, July 5, 2014

Automatic documentation generation using YARD

I wanted to automatically generate documentation for a blackjack game that I wrote for Tealeaf Academy's Ruby course using Sinatra.

RDoc seems to be the more popular documentation generator for Ruby, but I chose to use another program, called YARD. Here are my reasons:

  • Unlike RDoc, which expects totally free form comments, YARD provides a syntax to specify parameters, return types, and other details and generates consistently formatted output.
  • Using that syntax, it's possible to document a block of code, like a Sinatra route, as a method, even when it's really not.
  • YARD is backwards compatible with RDoc.

Here are the steps I took.

Add the YARD gem to the project

Add to the Gemfile and run

Refactor from classic Sinatra style to modular Sinatra style.

The game was originally written as a classic Sinatra application, meaning that the routes and helpers are defined in the top level namespace (More details), rather than in an application class. YARD documents things in the top level namespace, but doesn't include them in the index, which sort of defeats the purpose of documentation.

To convert a classical application to a modular one, we need to require 'sinatra/base' instead of 'sinatra' and to wrap the application in a class declaration. Then, we change the config.ru file in the root directory. It should now read (assuming the application class is defined in my_app.rb)

Extract helper methods to a module

In a classic Sinatra app, the helper methods are wrapped inside a do-end block. Although YARD can be made to recognize code blocks as methods, it won't recognize a method defined within a code block. To document the helper methods, we need to extract them to their own module.

Document methods and routes

YARD generates hyper-linked html documentation of classes, modules, and methods from Ruby comments. To be processed by YARD, the comments need to follow a specified format.

In general, a line of comments describes some attribute of the code below. Most lines begin with a tag, which starts with an @ sign. The tag specifies the placement and formatting of the text that follows. There are tags for method names and descriptions, parameter and return value names and data types, author names, and many others. Descriptions can be hyperlinked to other descriptions. To document a method, the syntax is This will result in html that renders to something like this.

To document a Sinatra route, we need to use the @overload tag. For example, will document the route as a method named

Generate documentation

Run in the root directory to create the documentation in the /doc folder.