You need to enable JavaScript to run this app. 如何为含yield的方法编写YARD文档 关联方法与代码块返回类型
优惠活动
大模型
产品
解决方案
定价
更多

如何为含yield的方法编写YARD文档 关联方法与代码块返回类型

YARD 标注memoize方法返回类型的正确实现

YARD 原生支持建立方法返回值与块执行结果的类型关联,不需要自定义泛型占位符,具体实现逻辑和优化方案如下:

核心机制说明

  • YARD 的类型解析器会自动关联块返回值与方法返回值:当方法的执行逻辑完全透传块的执行结果时,@yieldreturn 标签标注的块返回类型,会被同步识别为方法的合法返回类型,无需手动重复声明一致的类型条目。
  • 自定义 <T> 类占位符的写法不符合现有YARD规范:目前YARD的泛型语法仅支持集合类结构的类型标注(如 Array[Integer]、Hash{Symbol => String}),未定义的自定义占位符会被文档生成器解析为实际类名,产生错误的文档内容。

完善后的标注示例

匹配当前memoize方法逻辑的完整YARD注释可直接写为:

# Ensures that given block is only executed exactly once and on subsequent
# calls returns result from first execution. Useful for memoizing methods.
#
# @param key [Symbol]
#   Name or unique identifier of the method that is being memoized
# @yield The block to be executed only on the first call matching the provided key
# @yieldreturn [Object]
#   The arbitrary value produced by the block when first run
# @return [Object]
#   The exact value returned by the passed block; cached in the internal
#   memo store after first execution, subsequent calls with the same `key`
#   will return this cached value without re-running the block
def memoize(key, &_block)
  return @memos[key] if @memos.key?(key)

  @memos[key] = yield
end

优化建议

  • 通用memoize方法标注为Object类型完全符合实际行为:该方法是通用工具方法,块返回值完全由调用方决定,没有固定的返回类型边界,泛型占位符反而会增加文档理解成本。
  • 如需明确返回值与块的关联关系,可以在方法的描述段落补充说明 "The returned value is always identical to the result produced by the passed execution block",不需要额外添加不符合规范的语法占位符。
  • 针对具体调用memoize的业务方法,可以单独为每个业务方法标注明确的返回类型,不需要依赖通用memoize方法的跨调用类型推断。

内容的提问来源于stack exchange,提问作者Nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 04:06:10