You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用YARD无冗余记录子类重写的方法?

如何用YARD无冗余记录子类重写的方法

问题场景

现有如下Ruby代码,父类Parent的parent?方法已用YARD注释,但子类Child重写该方法后,YARD生成的文档既不显示父类的注释内容,也未标注该方法是重写而来的:

class Parent
  # Is this the parent?
  # @return [Boolean]
  def parent?
    true
  end
end

class Child < Parent
  def parent?
    false
  end
end

当前生成的文档存在两个问题:

  • Child#parent?没有继承父类的注释文本
  • 未明确标注该方法是重写自父类的方法

期望生成的文档效果:

Class: Parent

Instance Method Summary

#parent? ⇒ Boolean

Is this the parent?.

Class: Child

Instance Method Summary

#parent? ⇒ Boolean

Is this the parent?.

Methods inherited from Parent

#parent?

要求无需在子类中重复复制父类的注释内容。

解决方案

使用YARD的@inherit_doc标签,让子类重写的方法自动继承父类的文档注释,同时明确标注重写关系:

修改后的代码如下:

class Parent
  # Is this the parent?
  # @return [Boolean]
  def parent?
    true
  end
end

class Child < Parent
  # @inherit_doc
  def parent?
    false
  end
end

效果说明

  1. @inherit_doc会让YARD自动将父类Parent#parent?的注释内容(包括描述文本和@return标签)继承到Child#parent?的文档中,无需手动复制
  2. 生成的文档会明确标注Child#parent?是重写自Parent类的方法,同时在子类的方法列表中显示完整的继承文档
  3. 若需要补充子类特有的说明,可以在@inherit_doc之后添加额外注释,YARD会将父类文档和子类补充内容合并显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:10:34