如何用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? ⇒ BooleanIs this the parent?.
Class: Child
Instance Method Summary
#parent? ⇒ BooleanIs 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
效果说明
@inherit_doc会让YARD自动将父类Parent#parent?的注释内容(包括描述文本和@return标签)继承到Child#parent?的文档中,无需手动复制- 生成的文档会明确标注
Child#parent?是重写自Parent类的方法,同时在子类的方法列表中显示完整的继承文档 - 若需要补充子类特有的说明,可以在
@inherit_doc之后添加额外注释,YARD会将父类文档和子类补充内容合并显示
内容的提问来源于stack exchange,提问作者Schwern
相关产品推荐
相关产品推荐

