提供 Elixir 文档编写指南,涵盖 @moduledoc、@doc、@typedoc、doctests、交叉引用和元数据,适用于添加或改进文档时使用。
Elixir 写入 Docs Q快速引用是一项面向实际任务的技能,主要用于参考: 语法, 获取, 何时使用;参考/ doctests. md. 交叉引用和连接语法;
该技能适合需要稳定复用相关能力的场景,可作为自动化工作流的一部分,也便于后续检查、调整和扩展。从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
| 主题 | 参考文档 |
|---|---|
| Doctests:语法、常见陷阱、适用场景 | references/doctests.md |
| 交叉引用与链接语法 | references/cross-references.md |
| 注释块(Admonitions)、格式化、标签页(tabs) | references/admonitions-and-formatting.md |
ExDoc 及 mix docs 等工具会从 @moduledoc 和 @doc 的第一段中提取摘要内容。请确保首句简洁、自包含,能独立传达核心信息。
# GOOD — 首句可作为独立摘要 @moduledoc """ Handles payment processing through Stripe and local ledger reconciliation. Wraps the Stripe API client and ensures each charge is recorded in the local ledger before returning a confirmation to the caller. """ # BAD — 首句含糊,迫使读者继续阅读 @moduledoc """ This module contains various functions related to payments. It uses Stripe and also updates the ledger. """
该规则同样适用于 @doc:
# GOOD
@doc """
Charges a customer's default payment method for the given amount in cents.
Returns `{:ok, charge}` on success or `{:error, reason}` when the payment
gateway rejects the request.
"""
# BAD
@doc """
This function is used to charge a customer.
"""
@moduledoc 结构规范结构良好的 @moduledoc 应遵循以下模式:
defmodule MyApp.Inventory do
@moduledoc """
Tracks warehouse stock levels and triggers replenishment orders.
This module maintains an ETS-backed cache of current quantities and
exposes functions for atomic stock adjustments. It is designed to be
started under a supervisor and will restore state from the database
on init.
## Examples
iex> {:ok, pid} = MyApp.Inventory.start_link(warehouse: :east)
iex> MyApp.Inventory.current_stock(pid, "SKU-1042")
{:ok, 350}
## Configuration
Expects the following in `config/runtime.exs`:
config :my_app, MyApp.Inventory,
repo: MyApp.Repo,
low_stock_threshold: 50
"""
end
关键要点:
## Examples 展示真实可用的调用示例;若示例可执行,请优先使用 doctest。## Configuration 文档化必需的配置项;若模块无需配置,请省略此节。##);一级标题(#)在 ExDoc 输出中专用于模块名。定义 behaviour 时,应明确说明预期实现的回调函数:
defmodule MyApp.PaymentGateway do
@moduledoc """
Behaviour for payment gateway integrations.
Implementations must handle charging, refunding, and status checks.
See `MyApp.PaymentGateway.Stripe` for a reference implementation.
## Callbacks
* `charge/2` - Initiate a charge for a given amount
* `refund/2` - Refund a previously completed charge
* `status/1` - Check the status of a transaction
"""
@callback charge(amount :: pos_integer(), currency :: atom()) ::
{:ok, transaction_id :: String.t()} | {:error, term()}
@callback refund(transaction_id :: String.t(), amount :: pos_integer()) ::
:ok | {:error, term()}
@callback status(transaction_id :: String.t()) ::
{:pending | :completed | :failed, map()}
end
@doc 结构规范@doc """
Reserves the given quantity of an item, decrementing available stock.
Returns `{:ok, reservation_id}` when stock is available, or
`{:error, :insufficient_stock}` when the requested quantity exceeds
what is on hand.
## Examples
iex> MyApp.Inventory.reserve("SKU-1042", 5)
{:ok, "res_abc123"}
iex> MyApp.Inventory.reserve("SKU-9999", 1)
{:error, :not_found}
## Options
* `:warehouse` - Target warehouse atom. Defaults to `:primary`.
* `:timeout` - Timeout in milliseconds. Defaults to `5_000`.
"""
@spec reserve(String.t(), pos_integer(), keyword()) ::
{:ok, String.t()} | {:error, :insufficient_stock | :not_found}
def reserve(sku, quantity, opts \ []) do
# ...
end
编写指南:
## Options 小节中逐一说明各选项。@spec 应置于 @doc 与 def 之间,这是约定俗成的顺序。@typedoc请为使用 @type 或 @opaque 定义的自定义类型添加文档:
@typedoc """
A positive integer representing an amount in the smallest currency unit (e.g., cents).
"""
@type amount :: pos_integer()
@typedoc """
Reservation status returned by `status/1`.
* `:held` - Stock is reserved but not yet shipped
* `:released` - Reservation was cancelled and stock restored
* `:fulfilled` - Items have shipped
"""
@type reservation_status :: :held | :released | :fulfilled
@typedoc """
Opaque handle returned by `connect/1`. Do not pattern-match on this value.
"""
@opaque connection :: %__MODULE__{socket: port(), buffer: binary()}
对于 @opaque 类型,@typedoc 尤其重要,因为调用方无法检查其内部结构。
@doc since 与 @doc deprecated@doc since: "1.3.0" @doc """ Transfers stock between two warehouses. """ def transfer(from, to, sku, quantity), do: # ... @doc deprecated: "Use transfer/4 instead" @doc """ Moves items between locations. Deprecated in favor of `transfer/4` which supports cross-region transfers. """ def move_stock(from, to, sku, quantity), do: # ...
元数据与文档字符串可合并为单个属性:
@doc since: "2.0.0", deprecated: "Use bulk_reserve/2 instead" @doc """ Reserves multiple items in a single call. """ def batch_reserve(items), do: # ...
@moduledoc since: 对模块同样有效:
@moduledoc since: "1.2.0" @moduledoc """ Handles webhook signature verification for Stripe events. """
@doc false / @moduledoc false当模块或函数不属于公共 API 时,应屏蔽其文档生成:
# 私有实现模块 —— 仅限应用内部使用 defmodule MyApp.Inventory.StockCache do @moduledoc false # ... end # 协议实现 —— 文档由协议本身统一维护 defimpl String.Chars, for: MyApp.Money do @moduledoc false # ... end # 回调实现 —— 文档由 behaviour 统一维护 @doc false def handle_info(:refresh, state) do # ... end # 仅在当前模块内使用的辅助函数 @doc false def do_format(value), do: # ...
切勿对真正公开的函数使用 @doc false。 若函数已导出且被外部调用者依赖,则必须为其编写文档;若本不应被外部调用,请改用 defp 声明为私有函数。
文档(@moduledoc、@doc) |
代码注释(#) |
|
|---|---|---|
| 受众 | 你的 API 使用者 | 阅读源码的开发者 |
| 目的 | 契约声明:功能是什么、返回值是什么 | 解释特定实现选择的原因 |
| 是否渲染 | 是,在 HTML/epub 等 ExDoc 输出中可见 | 否,仅在源码中可见 |
| 是否必需 | 所有公开模块与函数均需提供 | 仅在代码意图不明显时才需添加 |
@doc """
Validates that the given coupon code is active and has remaining uses.
"""
@spec validate_coupon(String.t()) :: {:ok, Coupon.t()} | {:error, :expired | :exhausted}
def validate_coupon(code) do
# We query the read replica here to avoid adding load to the
# primary during high-traffic discount events.
Repo.replica().get_by(Coupon, code: code)
|> check_expiry()
|> check_remaining_uses()
end
@doc 向调用者说明 validate_coupon/1 的功能与返回值;而内联注释则解释了一个可能令人意外的实现决策。
请按以下顺序完成最终校验。若某步骤不适用,可跳过。
mix test,或完整测试套件)。通过标准:无 doctest 失败。m: 链接? 运行 mix docs。通过标准:命令成功完成;并解决 ExDoc 关于缺失模块、回调或无效链接的所有警告。def / defmacro 均显式标注了 @doc 或 @doc false;每个公开模块均标注了 @moduledoc 或 @moduledoc false,且符合项目既定策略。相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 134.1万人学习
共49课时 | 82.6万人学习
最新文章