Beautiful standardized RDoc comments for your Ruby / Rails methods

When I started working in Ruby on Rails five years ago, one thing that struck me was that there seemed to be no standard style for method documentation. Javadoc documentation, by contrast, is fairly uniform in the Java world.

I share with you today the template that I employ for documenting Ruby methods. I like this template because it, like Javadoc, creates a somewhat standard, easily readable comment structure.

  #
  #
  # * *Args*    :
  #   - ++ ->
  # * *Returns* :
  #   -
  # * *Raises* :
  #   - ++ ->
  #
  def method_name

  end

Here’s some toy code to demonstrate how the docs might appear when filled in.

  # This is an example method commented the way I like. 
  # It sums the three arguments and returns that value.
  #
  # Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
  # do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
  # Ut enim ad minim veniam, quis nostrud exercitation ullamco 
  # laboris nisi ut aliquip ex ea commodo consequat.
  #
  # * *Args*    :
  #   - +apples+ -> the number of apples
  #   - +oranges+ -> the number of oranges
  #   - +pears+ -> the number of pears
  # * *Returns* :
  #   - the total number of fruit as an integer
  # * *Raises* :
  #   - +ArgumentError+ -> if any value is nil or negative
  #
  def sum_fruit(apples, oranges, pears)
    raise ArgumentError, "No value can be absent" unless (apples.present? && oranges.present? && pears.present?)
    raise ArgumentError, "All values must be positive" unless (apples >= 0 && oranges >= 0 && pears >= 0)

    return apples+oranges+pears
  end

Not only is that strikingly readable, it also looks very nice when you run the rake doc:app task:

If you work in TextMate, you can save above code template as a custom “Snippet” under the Ruby language. I find it very handy to trigger with defc TAB. The actual snippet code is:

#
#
# * *Args*    :
#   - ++ ->
# * *Returns* :
#   -
# * *Raises* :
#   - ++ ->
#
def ${1:method_name}
	$0
end

2 thoughts on “Beautiful standardized RDoc comments for your Ruby / Rails methods

  1. Very nice template I must admit, personally I attach great importance to the documentation and I think over time you end up getting used and be very strict about when a problem arises, you will be more than grateful to have documented.

  2. Pingback: Commenting and Documentation in Ruby and Rails – Accumulative Effect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s