O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.11. Documenting Your Application

Problem

You want to create a set of API documentation for your application. You might want to go so far as to keep all your documentation in the same files as your source code.

Solution

It's good programming practice to preface each of your methods, classes, and modules with a comment that lets the reader know what's going on. Ruby rewards this behavior by making it easy to transform those comments into a set of HTML pages that document your code. This is similar to Java's JavaDoc, Python's PyDoc, and Perl's Pod.

Here's a simple example. Suppose your application contains only one file, sum.rb, which defines only one method:

	def sum(*terms)
	  terms.inject(0) { |sum, term| sum + term}
	end

To document this application, use Ruby comments to document the method, and also to document the file as a whole:

	# Just a simple file that defines a sum method.

	# Takes any number of numeric terms and returns the sum.
	#   sum(1, 2, 3)                             # => 6
	#   sum(1, -1, 10)                           # => 10
	#   sum(1.5, 0.2, 0.3, 1)                    # => 3.0
	def sum(*terms)
	  terms.inject(0) { |sum, term| sum + term}
	end

Change into the directory containing the sum.rb file, and run the rdoc command.

	$ rdoc
	sum.rb: .
	Generating HTML…

	Files: 1
	Classes: 0
	Modules: 0
	Methods: 1
	Elapsed: 0.101s

The rdoc command creates a doc/ subdirectory beneath the current directory. It parses every Ruby file it can find in or below the current directory, and generates HTML files from the Ruby code and the comments that document it.

The index.html ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required