File: api_documentation_guidelines.md

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (491 lines) | stat: -rw-r--r-- 15,125 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**

API Documentation Guidelines
============================

This guide documents the Ruby on Rails API documentation guidelines.

After reading this guide, you will know:

* How to write effective prose for documentation purposes.
* Style guidelines for documenting different kinds of Ruby code.

--------------------------------------------------------------------------------

RDoc
----

The [Rails API documentation](https://api.rubyonrails.org) is generated with
[RDoc](https://ruby.github.io/rdoc/). To generate it, make sure you are
in the rails root directory, run `bundle install` and execute:

```bash
$ bundle exec rake rdoc
```

Resulting HTML files can be found in the `./doc/rdoc` directory.

NOTE: Please consult the [RDoc Markup Reference][] for help with the syntax.

Links
-----

Rails API documentation are not meant to be viewed on GitHub and therefore links should use the [RDoc link markup][] markup relative to the current API.

This is due to differences between GitHub Markdown and the generated RDoc that is published at [api.rubyonrails.org](https://api.rubyonrails.org) and [edgeapi.rubyonrails.org](https://edgeapi.rubyonrails.org).

For example, we use `[link:classes/ActiveRecord/Base.html]` to create a link to the `ActiveRecord::Base` class generated by RDoc.

This is preferred over absolute URLs such as `[https://api.rubyonrails.org/classes/ActiveRecord/Base.html]`, which would take the reader outside their current documentation version (e.g. edgeapi.rubyonrails.org).

[RDoc Markup Reference]: https://ruby.github.io/rdoc/RDoc/MarkupReference.html
[RDoc link markup]: https://ruby.github.io/rdoc/RDoc/MarkupReference.html#class-RDoc::MarkupReference-label-Links

Wording
-------

Write simple, declarative sentences. Brevity is a plus. Get to the point.

```ruby
# BAD
# Caching may interfere with being able to see the results
# of code changes.

# GOOD
# Caching interferes with seeing the results of code changes.
```

Use present tense:

```ruby
# BAD
# Returned a hash that...
# Will return a hash that...
# Return a hash that...

# GOOD
# Returns a hash that...
```

Start comments in upper case. Follow regular punctuation rules:

```ruby
# BAD
# declares an attribute reader backed by an internally-named
# instance variable

# GOOD
# Declares an attribute reader backed by an internally-named
# instance variable.
```

Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the idioms recommended in edge. Reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.

```ruby
# BAD
# Book.where('name = ?', "Where the Wild Things Are")
# Book.where('year_published < ?', 50.years.ago)

# GOOD
# Book.where(name: "Where the Wild Things Are")
# Book.where(year_published: ...50.years.ago)
```

Documentation has to be brief but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?

### Naming

The proper names of Rails components have a space in between the words, like "Active Support". `ActiveRecord` is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper names.

```ruby
# GOOD
# Active Record classes can be created by inheriting from
# ActiveRecord::Base.
```

When referencing a "Rails application", as opposed to an "engine" or "plugin", always use "application". Rails apps are not "services", unless specifically discussing about service-oriented architecture.

```ruby
# BAD
# Production services can report their status upstream.
# Devise is a Rails authentication application.

# GOOD
# Production applications can report their status upstream.
# Devise is a Rails authentication engine.
```

Spell software names correctly. When in doubt, please have a look at some authoritative source like their official documentation.

```ruby
# GOOD
# Arel
# ERB
# Hotwire
# HTML
# JavaScript
# minitest
# MySQL
# npm
# PostgreSQL
# RSpec
```

Use the article "an" for "SQL":

```ruby
# BAD
# Creates a SQL statement.
# Starts a SQLite database.

# GOOD
# Creates an SQL statement.
# Starts an SQLite database.
```

### Pronouns

Prefer wordings that avoid "you"s and "your"s.

```ruby
# BAD
# If you need to use +return+ statements in your callbacks, it is
# recommended that you explicitly define them as methods.

# GOOD
# If +return+ is needed, it is recommended to explicitly define a
# method.
```

That said, when using pronouns in reference to a hypothetical person, such as "a
user with a session cookie", gender neutral pronouns (they/their/them) should be
used. Instead of:

* he or she... use they.
* him or her... use them.
* his or her... use their.
* his or hers... use theirs.
* himself or herself... use themselves.

### American English

Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).

### Oxford Comma

Please use the [Oxford comma](https://en.wikipedia.org/wiki/Serial_comma)
("red, white, and blue", instead of "red, white and blue").

Example Code
------------

Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.

For proper rendering, indent code by two spaces from the left margin. The examples themselves should use [Rails coding conventions](contributing_to_ruby_on_rails.html#follow-the-coding-conventions).

Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:

```ruby
# Converts a collection of elements into a formatted string by
# calling +to_s+ on all elements and joining them.
#
#   Blog.all.to_fs # => "First PostSecond PostThird Post"
```

On the other hand, big chunks of structured documentation may have a separate "Examples" section:

```ruby
# ==== Examples
#
#   Person.exists?(5)
#   Person.exists?('5')
#   Person.exists?(name: "David")
#   Person.exists?(['name LIKE ?', "%#{query}%"])
```

The results of expressions follow them and are introduced by "# => ", vertically aligned:

```ruby
# For checking if an integer is even or odd.
#
#   1.even? # => false
#   1.odd?  # => true
#   2.even? # => true
#   2.odd?  # => false
```

If a line is too long, the comment may be placed on the next line:

```ruby
#   label(:article, :title)
#   # => <label for="article_title">Title</label>
#
#   label(:article, :title, "A short title")
#   # => <label for="article_title">A short title</label>
#
#   label(:article, :title, "A short title", class: "title_label")
#   # => <label for="article_title" class="title_label">A short title</label>
```

Avoid using any printing methods like `puts` or `p` for that purpose.

On the other hand, regular comments do not use an arrow:

```ruby
#   polymorphic_url(record)  # same as comment_url(record)
```

### SQL

When documenting SQL statements, the result should not have `=>` before the output.

For example,

```ruby
#   User.where(name: 'Oscar').to_sql
#   # SELECT "users".* FROM "users"  WHERE "users"."name" = 'Oscar'
```

### IRB

When documenting the behavior for IRB, Ruby's interactive REPL, always prefix commands with `irb>`. The output should be prefixed with `=>`.

For example,

```ruby
# Find the customer with primary key (id) 10.
#   irb> customer = Customer.find(10)
#   # => #<Customer id: 10, first_name: "Ryan">
```

### Bash / Command-line

For command-line examples, always prefix the command with `$`. The output doesn't have to be prefixed with anything.

```ruby
# Run the following command:
#   $ bin/rails new zomg
#   ...
```

Booleans
--------

For predicates and flags, prefer documenting boolean semantics over exact values.

When "true" or "false" are used as defined in Ruby use regular font. The
singletons `true` and `false` need fixed-width font. Please avoid terms like
"truthy". Ruby defines what is true and false in the language, and thus those
words have a technical meaning and need no substitutes.

As a rule of thumb, do not document singletons unless absolutely necessary. That
prevents artificial constructs like `!!` or ternaries, allows refactors, and the
code does not need to rely on the exact values returned by methods being called
in the implementation.

For example:

```ruby
# +config.action_mailer.perform_deliveries+ specifies whether mail
# will actually be delivered and is true by default
```

the user does not need to know which is the actual default value of the flag,
and so we only document its boolean semantics.

An example with a predicate:

```ruby
# Returns true if the collection is empty.
#
# If the collection has been loaded it is equivalent to
# +collection.size.zero?+. If the collection has not been loaded,
# it is equivalent to +!collection.exists?+. If the collection has
# not already been loaded and you are going to fetch the records
# anyway, it is better to check +collection.length.zero?+.
def empty?
  if loaded?
    size.zero?
  else
    @target.blank? && !scope.exists?
  end
end
```

The API is careful not to commit to any particular value, the method has
predicate semantics, which is sufficient.

File Names
----------

As a rule of thumb, use filenames relative to the application root:
`config/routes.rb` instead of `routes.rb` or `RAILS_ROOT/config/routes.rb`.

Fonts
-----

### Fixed-width Font

Use fixed-width fonts for:

* Constants, in particular class and module names
* Method names
* Literals like `nil`, `false`, `true`, `self`
* Symbols
* Method parameters
* File names
* HTML tags and attributes
* CSS selectors, attributes and values

```ruby
class Array
  # Calls +to_param+ on all its elements and joins the result with
  # slashes. This is used by +url_for+ in Action Pack.
  def to_param
    collect { |e| e.to_param }.join '/'
  end
end
```

WARNING: Using `+...+` for fixed-width font only works with simple content like
ordinary classes, modules, method names, symbols, paths (with forward slashes),
etc. Use `<tt>...</tt>` for everything else.

You can quickly test the RDoc output with the following command:

```bash
$ echo "+:to_param+" | rdoc --pipe
# => <p><code>:to_param</code></p>
```

For example, code with spaces or quotes should use the `<tt>...</tt>` form.

### Regular Font

When "true" and "false" are English words rather than Ruby keywords use a regular font:

```ruby
# Runs all the validations within the specified context.
# Returns true if no errors are found, false otherwise.
#
# If the argument is false (default is +nil+), the context is
# set to <tt>:create</tt> if <tt>new_record?</tt> is true,
# and to <tt>:update</tt> if it is not.
#
# Validations with no <tt>:on</tt> option will run no
# matter the context. Validations with # some <tt>:on</tt>
# option will only run in the specified context.
def valid?(context = nil)
  # ...
end
```

Description Lists
-----------------

In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):

```ruby
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
```

The description starts in upper case and ends with a full stop—it's standard English.

An alternative approach, when you want to provide additional detail and examples is to use option section style.

[`ActiveSupport::MessageEncryptor#encrypt_and_sign`][#encrypt_and_sign] is a great example of this.

```ruby
# ==== Options
#
# [+:expires_at+]
#   The datetime at which the message expires. After this datetime,
#   verification of the message will fail.
#
#     message = encryptor.encrypt_and_sign("hello", expires_at: Time.now.tomorrow)
#     encryptor.decrypt_and_verify(message) # => "hello"
#     # 24 hours later...
#     encryptor.decrypt_and_verify(message) # => nil
```

[#encrypt_and_sign]: https://api.rubyonrails.org/classes/ActiveSupport/MessageEncryptor.html#method-i-encrypt_and_sign

Dynamically Generated Methods
-----------------------------

Methods created with `(module|class)_eval(STRING)` have a comment by their side with an instance of the generated code. That comment is 2 spaces away from the template:

[![(module|class)_eval(STRING) code comments](images/dynamic_method_class_eval.png)](images/dynamic_method_class_eval.png)

If the resulting lines are too wide, say 200 columns or more, put the comment above the call:

```ruby
# def self.find_by_login_and_activated(*args)
#   options = args.extract_options!
#   ...
# end
self.class_eval %{
  def self.#{method_id}(*args)
    options = args.extract_options!
    ...
  end
}, __FILE__, __LINE__
```

Method Visibility
-----------------

When writing documentation for Rails, it's important to differentiate between
the user-facing API and the internal API.

Methods that are in Ruby's private scope are excluded from the user-facing API.
However, some internal API methods must be in Ruby's public scope so that they
can be called elsewhere in the framework. To exclude such methods from the
user-facing API, use RDoc's `:nodoc:` directive.

An example is `ActiveRecord::Core::ClassMethods#arel_table`:

```ruby
module ActiveRecord::Core::ClassMethods
  def arel_table # :nodoc:
    # do some magic..
  end
end
```

Even though it is a public method, users should not rely on it. The name of this
method may change, or the return value may change, or this method may be removed
entirely. By marking it with `:nodoc:`, it is removed from the user-facing API
documentation.

As a contributor, it's important to think about whether an API should be
user-facing or internal. The Rails team is committed to not making breaking
changes to the user-facing API without first going through a full deprecation
cycle. Therefore, you should add `:nodoc:` to any internal methods or modules,
unless they are already private. (Adding `:nodoc:` to a module or class
indicates that all methods are internal API, and it should be removed from the
user-facing API documentation.)

Regarding the Rails Stack
-------------------------

When documenting parts of Rails' API, it's important to be mindful of the entire
Rails stack. Behavior of the method or class you're documenting may change
depending on context.

One such example is `ActionView::Helpers::AssetTagHelper#image_tag`:

```ruby
# image_tag("icon.png")
#   # => <img src="/assets/icon.png" />
```

In isolation, `image_tag` would return `/images/icon.png`. However, when we take
into account the full Rails stack, including the Asset Pipeline, we may see the
above result.

We want to document the behavior of the _framework_, not just isolated methods.
Our concern is the behavior that the user experiences when using the full
default Rails stack.

If you have a question on how the Rails team handles certain API, don't hesitate to open a ticket or send a patch to the [issue tracker](https://github.com/rails/rails/issues).