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:
- 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.
- 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. - 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. - 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 bothtrue
orfalse
, you should use theBoolean
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 avoid
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.
@api description
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.
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.
@attr name [Types] description
Use the more powerful @!attribute directive instead.
This attribute is only applicable on class docstrings
Declares a readwrite attribute on a Struct or class.
@attr_reader name [Types] description
Use the more powerful @!attribute directive instead.
This attribute is only applicable on class docstrings
Declares a readonly attribute on a Struct or class.
@attr_writer name [Types] description
Use the more powerful @!attribute directive instead.
This attribute is only applicable on class docstrings
Declares a writeonly attribute on a Struct or class.
@author description
List the author or authors of a class, module, or method.
@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.
@example Optional title
Code block
Show an example snippet of code for an object. The first line is an optional title.
@note description
Adds an emphasized note at the top of the docstring for the object
@option name [Types] option_key (default_value) description
For keyword parameters, use @param, not @option.
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.
@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.
@param name [Types] description
Documents a single method parameter (either regular or keyword) with a given name, type and optional description.
@private
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.
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.
@raise [Types] description
Describes that a method may raise a given exception, with an optional description of what it may mean.
@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 …”.
@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.
@since description
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.
@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
@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.
@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.
@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.
@yieldreturn [Types] description
Documents the value and type that the block is expected to return to the method.
Directive List
@!attribute [r | w | rw] attribute_name
Indented attribute docstring
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
@!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.
@!group description
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.
@!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.
@!method method_signature(parameters)
Indented method docstring
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
@!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”.
@!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.
@!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.