Tags Overview

Tags represent meta-data as well as behavioural data that can be added to documentation through the @tag style syntax. As mentioned, there are two basic types of tags in YARD, "meta-data tags" and "behavioural tags", the latter is more often known as "directives". These two tag types can be visually identified by their prefix. Meta-data tags have a @ prefix, while directives have a prefix of @! to indicate that the directive performs some potentially mutable action on or with the docstring. The two tag types would be used in the following way, respectively:

# @meta_data_tag some data
# @!directive_tag some data
class Foo; end

This document describes how tags can be specified, how they affect your documentation, and how to use specific built-in tags in YARD, as well as how to define custom tags.

Meta-Data Tags

Meta-data tags are useful to add arbitrary meta-data about a documented object. These tags simply add data to objects that can be looked up later, either programmatically, or displayed in templates. The benefit to describing objects using meta-data tags is that your documentation can be organized semantically. Rather than having a huge listing of text with no distinction of what each paragraph is discussing, tags allow you to focus in on specific elements of your documentation.

For example, describing parameters of a method can often be important to your documentation, but should not be mixed up with the documentation that describes what the method itself does. In this case, separating the parameter documentation into @param tags can yield much better organized documentation, both in source and in your output, without having to manually format the data using standard markup.

All of this meta-data can be easily parsed by tools and used both in your templates as well as in code checker tools. An example of how you can leverage tags programmatically is shown in the @todo tag, which lists a small snippet of Ruby code that can list all of your TODO items, if they are properly tagged.

Custom meta-data tags can be added either programmatically or via the YARD command-line. This is discussed in the "Adding Custom Tags" section.

A list of built-in meta-data tags are found below in the Tag List.

Directives

Directives are similar to meta-data tags in the way they are specified, but they do not add meta-data to the object directly. Instead, they affect the parsing context and objects themselves, allowing a developer to create objects (like methods) outright, rather than simply add text to an existing object. Directives have a @! prefix to differentiate these tags from meta-data tags, as well as to indicate that the tag may modify or create new objects when it is called.

A list of built-in directives are found below in the Directive List.

Tag Syntax

Tags begin with the @ or @! prefix at the start of a comment line, followed immediately by the tag name, and then optional tag data (if the tag requires it). Unless otherwise specified by documentation for the tag, all "description" text is considered free-form data and can include any arbitrary textual data.

Multi-line Tags

Tags can span multiple lines if the subsequent lines are indented by more than one space. The typical convention is to indent subsequent lines by 2 spaces. In the following example, @tagname will have the text "This is indented tag data":

# @tagname This is
#   indented tag data
# but this is not

For most tags, newlines and indented data are not significant and do not impact the result of the tag. In other words, you can decide to span a tag onto multiple lines at any point by creating an indented block. However, some tags like @example, @overload, @!macro, @!method, and @!attribute rely on the first line for special information about the tag, and you cannot split this first line up. For instance, the @example tag uses the first line to indicate the example's title.

Common Tag Syntaxes

Although custom tags can be parsed in any way, the built-in tags follow a few common syntax structures by convention in order to simplify the syntax. The following syntaxes are available:

  1. Freeform data — In this case, any amount of textual data is allowed, including no data. In some cases, no data is necessary for the tag.
  2. Freeform data with a types specifier list — Mostly freeform data beginning with an optional types specifier list surrounded in [brackets]. Note that for extensibility, other bracket types are allowed, such as <>, () and {}. The contents of the list are discussed in detail below.
  3. Freeform data with a name and types specifier list — freeform data beginning with an optional types list, as well as a name key. The name key is required. Note that for extensibility, the name can be placed before the types list, like: name [Types] description. In this case, a separating space is not required between the name and types, and you can still use any of the other brackets that the type specifier list allows.
  4. Freeform data with title — freeform data where the first line cannot be split into multiple lines. The first line must also always refer to the "title" portion, and therefore, if there is no title, the first line must be blank. The "title" might occasionally be listed by another name in tag documentation, however, you can identify this syntax by the existence of a multi-line signature with "Indented block" on the second line.

In the tag list below, the term "description" implies freeform data, [Types] implies a types specifier list, "name" implies a name key, and "title" implies the first line is a newline significant field that cannot be split into multiple lines.

Types Specifier List

In some cases, a tag will allow for a "types specifier list"; this will be evident from the use of the [Types] syntax in the tag signature. A types specifier list is a comma separated list of types, most often classes or modules, but occasionally literals. For example, the following @return tag lists a set of types returned by a method:

# Finds an object or list of objects in the db using a query
# @return [String, Array<String>, nil] the object or objects to
#   find in the database. Can be nil.
def find(query) finder_code_here end

A list of conventions for type names is specified below. Typically, however, any Ruby literal or class/module is allowed here. Duck-types (method names prefixed with "#") are also allowed.

Note that the type specifier list is always an optional field and can be omitted when present in a tag signature. This is the reason why it is surrounded by brackets. It is also a freeform list, and can contain any list of values, though a set of conventions for how to list types is described below.

Type List Conventions

A list of examples of common type listings and what they translate into is available at http://yardoc.org/types.

Typically, a type list contains a list of classes or modules that are associated with the tag. In some cases, however, certain special values are allowed or required to be listed. This section discusses the syntax for specifying Ruby types inside of type specifier lists, as well as the other non-Ruby types that are accepted by convention in these lists.

It's important to realize that the conventions listed here may not always adequately describe every type signature, and is not meant to be a complete syntax. This is why the types specifier list is freeform and can contain any set of values. The conventions defined here are only conventions, and if they do not work for your type specifications, you can define your own appropriate conventions.

Note that a types specifier list might also be used for non-Type values. In this case, the tag documentation will describe what values are allowed within the type specifier list.

Class or Module Types

Any Ruby type is allowed as a class or module type. Such a type is simply the name of the class or module.

Note that one extra type that is accepted by convention is the Boolean type, which represents both the TrueClass and FalseClass types. This type does not exist in Ruby, however.

Parametrized Types

In addition to basic types (like String or Array), YARD conventions allow for a "generics" like syntax to specify container objects or other parametrized types. The syntax is Type<SubType, OtherSubType, ...>. For instance, an Array might contain only String objects, in which case the type specification would be Array<String>. Multiple parametrized types can be listed, separated by commas.

Note that parametrized types are typically not order-dependent, in other words, a list of parametrized types can occur in any order inside of a type. An array specified as Array<String, Fixnum> can contain any amount of Strings or Fixnums, in any order. When the order matters, use "order-dependent lists", described below.

Duck-Types

Duck-types are allowed in type specifier lists, and are identified by method names beginning with the "#" prefix. Typically, duck-types are recommended for @param tags only, though they can be used in other tags if needed. The following example shows a method that takes a parameter of any type that responds to the "read" method:

# Reads from any I/O object.
# @param [#read] io the input object to read from
def read(io) io.read end

Hashes

Hashes can be specified either via the parametrized type discussed above, in the form Hash<KeyType, ValueType>, or using the hash specific syntax: Hash{KeyTypes=>ValueTypes}. In the latter case, KeyTypes or ValueTypes can also be a list of types separated by commas.

Order-Dependent Lists

An order dependent list is a set of types surrounded by "()" and separated by commas. This list must contain exactly those types in exactly the order specified. For instance, an Array containing a String, Fixnum and Hash in that order (and having exactly those 3 elements) would be listed as: Array<(String, Fixnum, Hash)>.

Literals

Some literals are accepted by virtue of being Ruby literals, but also by YARD conventions. Here is a non-exhaustive list of certain accepted literal values:

  • true, false, nil — used when a method returns these explicit literal values. Note that if your method returns both true or false, you should use the Boolean conventional type instead.
  • self — has the same meaning as Ruby's "self" keyword in the context of parameters or return types. Recommended mostly for @return tags that are chainable.
  • void — indicates that the type for this tag is explicitly undefined. Mostly used to specify @return tags that do not care about their return value. Using a void return tag is recommended over no type, because it makes the documentation more explicit about what the user should expect. YARD will also add a note for the user if they have undefined return types, making things clear that they should not use the return value of such a method.

Reference Tags

Reference tag syntax applies only to meta-data tags, not directives.

If a tag's data begins with (see OBJECT) it is considered a "reference tag". A reference tag literally copies the tag data by the given tag name from the specified OBJECT. For instance, a method may copy all @param tags from a given object using the reference tag syntax:

# @param [String] user the username for the operation
# @param [String] host the host that this user is associated with
# @param [Time] time the time that this operation took place
def clean(user, host, time = Time.now) end

# @param (see #clean)
def activate(user, host, time = Time.now) end

Adding Custom Tags

If a tag is specific to a given project, consider namespacing it by naming it in the form projectname.tagname, ie., yard.tag_signature.

Custom tags can be added to YARD either via the command-line or programmatically. The programmatic method is not discussed in this document, but rather in the TagsArch document.

To add a custom tag via the command-line or .yardopts file, you can use the --*-tag options. A few different options are available for the common tag syntaxes described above. For example, to add a basic freeform tag, use:

$ yard doc --tag rest_url:"REST URL"

This will register the @rest_url tag for use in your documentation and display this tag in HTML output wherever it is used with the heading "REST URL". Note that the tag title should follow the tag name with a colon (:). Other tag syntaxes exist, such as the type specifier list freeform tag (--type-tag), or a named key tag with types (--type-name-tag).

If you want to create a tag but not display it in output (it is only for programmatic use), add --hide-tag tagname after the definition:

$ yard doc --tag complexity:"McCabe Complexity" --hide-tag complexity

Note that you might not need a tag title if you are hiding it. The title part can be omitted.

Tag List

@abstract description

Marks a class/module/method as abstract with optional implementor information.

Examples:

# @abstract Subclass and override {#run} to implement
#   a custom Threadable class.
class Runnable
  def run; raise NotImplementedError end
end

@api description

Note:

This tag is transitive. If it is applied on a namespace (module or class), it will automatically be applied to all children objects of that namespace unless it is redefined on the child object.

Note:

The special name @api private does display a notice in documentation if it is listed, letting users know that the method is not to be used by external components.

Declares the API that the object belongs to. Does not display in output, but useful for performing queries (+yardoc –query+). Any text is allowable in this tag, and there are no predefined values.

Examples:

class Post
  # @api private
  def reset_table!; table.flush end
end

@attr name [Types] description

Deprecated.

Use the more powerful @!attribute directive instead.

Note:

This attribute is only applicable on class docstrings

Declares a readwrite attribute on a Struct or class.

Examples:

# @attr [String] name the name of the structure
# @attr [Fixnum] size the size of the structure
class MyStruct < Struct; end

@attr_reader name [Types] description

Deprecated.

Use the more powerful @!attribute directive instead.

Note:

This attribute is only applicable on class docstrings

Declares a readonly attribute on a Struct or class.

Examples:

# @attr_reader [String] name the name of the structure
# @attr_reader [Fixnum] size the size of the structure
class MyStruct < Struct; end

@attr_writer name [Types] description

Deprecated.

Use the more powerful @!attribute directive instead.

Note:

This attribute is only applicable on class docstrings

Declares a writeonly attribute on a Struct or class.

Examples:

# @attr_reader [String] name the name of the structure
# @attr_reader [Fixnum] size the size of the structure
class MyStruct < Struct; end

@author description

List the author or authors of a class, module, or method.

Examples:

# @author Foo Bar 
class MyClass; end

@deprecated description

Marks a method/class as deprecated with an optional description. The description should be used to inform users of the recommended migration path, and/or any useful information about why the object was marked as deprecated.

Examples:

Deprecate a method with a replacement API

# @deprecated Use {#bar} instead.
def foo; end

Deprecate a method with no replacement

class Thread
  # @deprecated Exiting a thread in this way is not reliable and
  #   can cause a program crash.
  def kill; end
end

@example Optional title
   Code block

Show an example snippet of code for an object. The first line is an optional title.

Examples:

# @example Reverse a String
#   "mystring".reverse #=> "gnirtsym"
def reverse; end

@note description

Adds an emphasized note at the top of the docstring for the object

Examples:

# @note This method should only be used in outer space.
def eject; end

See Also:

@option name [Types] option_key (default_value) description

Describe an options hash in a method. The tag takes the name of the options parameter first, followed by optional types, the option key name, a default value for the key and a description of the option. The default value should be placed within parentheses and is optional (can be omitted).

Note that a @param tag need not be defined for the options hash itself, though it is useful to do so for completeness.

Examples:

# @param [Hash] opts the options to create a message with.
# @option opts [String] :subject The subject
# @option opts [String] :from ('nobody') From address
# @option opts [String] :to Recipient email
# @option opts [String] :body ('') The email's body
def send_email(opts = {}) end

@overload method_signature(parameters)
   Indented docstring for overload method

Describe that your method can be used in various contexts with various parameters or return types. The first line should declare the new method signature, and the following indented tag data will be a new documentation string with its own tags adding metadata for such an overload.

Examples:

# @overload set(key, value)
#   Sets a value on key
#   @param [Symbol] key describe key param
#   @param [Object] value describe value param
# @overload set(value)
#   Sets a value on the default key +:foo+
#   @param [Object] value describe value param
def set(*args) end

@param name [Types] description

Documents a single method parameter with a given name, type and optional description.

Examples:

# @param [String] the URL of the page to download
def load_page(url) end

@private

Note:

This method is not recommended for hiding undocumented or “unimportant” methods. This tag should only be used to mark objects private when Ruby visibility rules cannot do so. In Ruby 1.9.3, you can use private_constant to declare constants (like classes or modules) as private, and should be used instead of @private.

Note:

This tag is transitive. If it is applied on a namespace (module or class), it will automatically be applied to all children objects of that namespace unless it is redefined on the child object.

Declares that the logical visibility of an object is private. In other words, it specifies that this method should be marked private but cannot due to Ruby’s visibility restrictions. This exists for classes, modules and constants that do not obey Ruby’s visibility rules. For instance, an inner class might be considered “private”, though Ruby would make no such distinction.

This tag is meant to be used in conjunction with the --no-private command-line option, and is required to actually remove these objects from documentation output. See README for more information on switches.

If you simply want to set the API visibility of a method, you should look at the @api tag instead.

Examples:

# @private
class InteralImplementation; end

See Also:

@raise [Types] description

Describes that a method may raise a given exception, with an optional description of what it may mean.

Examples:

# @raise [AccountBalanceError] if the account does not have
#   sufficient funds to perform the transaction
def withdraw(amount) end

@return [Types] description

Describes the return value (and type or types) of a method. You can list multiple return tags for a method in the case where a method has distinct return cases. In this case, each case should begin with “if …”.

Examples:

A regular return value

# @return [Fixnum] the size of the file
def size; @file.size end

A method returns an Array or a single object

# @return [String] if a single object was returned
#   from the database.
# @return [Array] if multiple objects were
#   returned.
def find(query) end

@see name description

“See Also” references for an object. Accepts URLs or other code objects with an optional description at the end. Note that the URL or object will be automatically linked by YARD and does not need to be formatted with markup.

Examples:

# Synchronizes system time using NTP.
# @see http://ntp.org/documentation.html NTP Documentation
# @see NTPHelperMethods
class NTPUpdater; end

@since description

Note:

This tag is transitive. If it is applied on a namespace (module or class), it will automatically be applied to all children objects of that namespace unless it is redefined on the child object.

Lists the version that the object was first added.

Examples:

# @since 1.2.4
def clear_routes; end

@todo description

Marks a TODO note in the object being documented. For reference, objects with TODO items can be enumerated from the command line with a simple command:

mocker$ yard list --query '@todo'
lib/mocker/mocker.rb:15: Mocker
lib/mocker/report/html.rb:5: Mocker::Report::Html

YARD can also be used to enumerate the TODO items from a short script:

require 'yard'
YARD::Registry.load!.all.each do |o|
  puts o.tag(:todo).text if o.tag(:todo)
end

Examples:

# @todo Add support for Jabberwocky service.
#   There is an open source Jabberwocky library available
#   at http://jbrwcky.org that can be easily integrated.
class Wonderlander; end

See Also:

@version description

Lists the version of a class, module or method. This is similar to a library version, but at finer granularity. In some cases, version of specific modules, classes, methods or generalized components might change independently between releases. A version tag is used to infer the API compatibility of a specific object.

Examples:

# The public REST API for http://jbrwcky.org
# @version 2.0
class JabberwockyAPI; end

@yield [parameters] description

Describes what a method might yield to a given block. The types specifier list should not list types, but names of the parameters yielded to the block. If you define parameters with @yieldparam, you do not need to define the parameters in the type specification of @yield as well.

Examples:

# For a block {|a,b,c| ... }
# @yield [a, b, c] Gives 3 random numbers to the block
def provide3values(&block) yield(42, 42, 42) end

See Also:

@yieldparam name [Types] description

Defines a parameter yielded by a block. If you define the parameters with @yieldparam, you do not need to define them via @yield as well.

Examples:

# @yieldparam [String] name the name that is yielded
def with_name(name) yield(name) end

@yieldreturn [Types] description

Documents the value and type that the block is expected to return to the method.

Examples:

# @yieldreturn [Fixnum] the number to add 5 to.
def add5_block(&block) 5 + yield end

See Also:

Directive List

@!attribute [r | w | rw] attribute_name
   Indented attribute docstring

Note:

For backwards compatibility support, you do not need to indent the attribute’s docstring text. If an @!attribute directive is seen with no indented block, the entire docstring is used as the new attribute’s docstring text.

Defines an attribute with a given name, using indented block data as the attribute’s docstring. If the type specifier is supplied with “r”, “w”, or “rw”, the attribute is made readonly, writeonly or readwrite respectively. A readwrite attribute is the default, if no type is specified. The comment containing this directive does not need to be attached to any source, but if it is, that source code will be used as the method’s source.

To define an regular method, see @!method

Examples:

Defining a simple readonly attribute

# @!attribute [r] count
#   @return [Fixnum] the size of the list

Defining a simple readwrite attribute

# @!attribute name
#   @return [String] the name of the user

See Also:

Since:

  • 0.7.0

@!endgroup

Ends a group listing definition. Group definition automatically end when class or module blocks are closed, and defining a new group overrides the last group definition, but occasionally you need to end the current group to return to the default listing. Use @!group to begin a group listing.

Examples:

class Controller
  # @!group Callbacks

  def before_filter; end
  def after_filter; end

  # @!endgroup

  def index; end
end

See Also:

Since:

  • 0.6.0

@!group description

Note:

A group definition only applies to the scope it is defined in. If a new class or module is opened after the directive, this directive will not apply to methods in that class or module.

Defines a group listing. All methods (and attributes) seen after this directive are placed into a group with the given description as the group name. The group listing is used by templates to organize methods and attributes into respective logical groups. To end a group listing use @!endgroup.

Examples:

# @!group Callbacks

def before_filter; end
def after_filter; end

See Also:

Since:

  • 0.6.0

@!macro [attach | new] optional_name
   Optional macro expansion data

Defines a block of text to be expanded whenever the macro is called by name in subsequent docstrings. The macro data can be any arbitrary text data, be it regular documentation, meta-data tags or directives.

Defining a Macro

A macro must first be defined in order to be used. Note that a macro is also expanded upon definition if it defined on an object (the docstring of a method, class, module or constant object as opposed to a free standing comment). To define a macro, use the “new” or “attach” identifier in the types specifier list. A macro will also automatically be created if an indented macro data block is given, so the keywords are not strictly needed.

Anonymous Macros

In addition to standard named macros, macros can be defined anonymously if no name is given. In this case, they can not be re-used in future docstrings, but they will expand in the first definition. This is useful when needing to take advantage of the macro expansion variables (described below).

Using a Macro

To re-use a macro in another docstring after it is defined, simply use @!macro the_name with no indented block of macro data. The resulting data will be expanded in place.

Attaching a Macro to a DSL Method

Macros can be defined to auto-expand on DSL-style class method calls. To define a macro to be auto expanded in this way, use the “attach” keyword in the type specifier list (“new” is implied).

Attached macros can also be attached directly on the class method declaration that provides the DSL method to its subclasses. The syntax in either case is the same.

Macro Expansion Variables

In the case of using macros on DSL-style method calls, a number of expansion variables can be used for interpolation inside of the macro data. The variables, similar in syntax to Ruby’s global variables, are as follows:

  • $0 - the method name being called

  • $1, $2, $3, … - the Nth argument in the method call

  • $& - the full source line

The following example shows what the expansion variables might hold for a given DSL method call:

property :foo, :a, :b, :c, String
# $0 => "property"
# $1 => "foo"
# $2 => "a"
# $& => "property :foo, :a, :b, :c, String"

Ranges

Ranges are also acceptable with the syntax ${N-M}. Negative values on either N or M are valid, and refer to indexes from the end of the list. Consider a DSL method that creates a method using the first argument with argument names following, ending with the return type of the method. This could be documented as:

# @!macro dsl_method
#   @!method $1(${2--2})
#   @return [${-1}] the return value of $0
create_method_with_args :foo, :a, :b, :c, String

As described, the method is using the signature foo(a, b, c) and the return type from the last argument, String. When using ranges, tokens are joined with commas. Note that this includes using $0:

$0-1 # => Interpolates to "create_method_with_args, foo"

If you want to separate them with spaces, use $1 $2 $3 $4 .... Note that if the token cannot be expanded, it will return the empty string (not an error), so it would be safe to list $1 $2 ... $10, for example.

Escaping Interpolation

Interpolation can be escaped by prefixing the $ with \, like so:

# @!macro foo
#   I have \$2.00 USD.

Examples:

Defining a simple macro

# @!macro [new] returnself
#   @return [self] returns itself

Using a simple macro in multiple docstrings

# Documentation for map
# ...
# @macro returnself
def map; end

# Documentation for filter
# ...
# @macro returnself
def filter; end

Attaching a macro to a class method (for DSL usage)

class Resource
  # Defines a new property
  # @param [String] name the property name
  # @param [Class] type the property's type
  # @!macro [attach] property
  #   @return [$2] the $1 property
  def self.property(name, type) end
end

class Post < Resource
  property :title, String
  property :view_count, Integer
end

Attaching a macro directly to a DSL method

class Post < Resource
  # @!macro [attach] property
  #   @return [$2] the $1 property
  property :title, String

  # Macro will expand on this definition too
  property :view_count, Integer
end

Since:

  • 0.7.0

@!method method_signature(parameters)
   Indented method docstring

Note:

For backwards compatibility support, you do not need to indent the method’s docstring text. If a @!method directive is seen with no indented block, the entire docstring is used as the new method’s docstring text.

Defines a method object with a given method signature, using indented block data as the method’s docstring. The signature is similar to the @overload tag. The comment containing this directive does not need to be attached to any source, but if it is, that source code will be used as the method’s source.

To define an attribute method, see @!attribute

Examples:

Defining a simple method

# @!method quit(username, message = "Quit")
#   Sends a quit message to the server for a +username+.
#   @param [String] username the username to quit
#   @param [String] message the quit message
quit_message_method

Attaching multiple methods to the same source

# @!method method1
# @!method method2
create_methods :method1, :method2

See Also:

Since:

  • 0.7.0

@!parse [language] code

Parses a block of code as if it were present in the source file at that location. This directive is useful if a class has dynamic meta-programmed behaviour that cannot be recognized by YARD.

You can specify the language of the code block using the types specification list. By default, the code language is “ruby”.

Examples:

Documenting dynamic module inclusion

class User
  # includes "UserMixin" and extends "UserMixin::ClassMethods"
  # using the UserMixin.included callback.
  # @!parse include UserMixin
  # @!parse extend UserMixin::ClassMethods
end

Declaring a method as an attribute

# This should really be an attribute
# @!parse attr_reader :foo
def object; @parent.object end

Parsing C code

# @!parse [c]
#   void Init_Foo() {
#     rb_define_method(rb_cFoo, "method", method, 0);
#   }

Since:

  • 0.8.0

@!scope class | instance

Modifies the current parsing scope (class or instance). If this directive is defined on a docstring attached to an object definition, it is applied only to that object. Otherwise, it applies the scope to all future objects in the namespace.

Examples:

Modifying the scope of a DSL method

# @!scope class
cattr_accessor :subclasses

Modifying the scope of a set of methods

# @!scope class

# Documentation for method1
def method1; end

# Documentation for method2
def method2; end

Since:

  • 0.7.0

@!visibility public | protected | private

Modifies the current parsing visibility (public, protected, or private). If this directive is defined on a docstring attached to an object definition, it is applied only to that object. Otherwise, it applies the visibility to all future objects in the namespace.

Examples:

Modifying the visibility of a DSL method

# @!visibility private
cattr_accessor :subclasses

Modifying the visibility of a set of methods

# Note that Ruby's "protected" is recommended over this directive
# @!visibility protected

# Documentation for method1
def method1; end

# Documentation for method2
def method2; end

Since:

  • 0.7.0