如何在YARD中引用当前类作为返回类型?

时间:2019-05-24 07:18:39

标签: ruby yard

考虑这样的代码:

module Foo
  # returns a copy of self
  # @return [ ___ ]
  def returns_new_self
    self.class.new
  end
end

class Bar
  include Foo
end

class Zap
  include Foo
end

这样,Bar.new.returns_new_self将返回另一个BarZap.new.returns_new_self也是如此。

我想记录retuns_new_self码的返回类型。
如果我可以像Rust中的@return [Self]一样做Self之类的事情,那将是很好的事情。

我可以做类似的事情吗?


编辑:(回复@spickermann)

实际代码如下:

module MultipleItemBehaviour
  # @return [Integer]
  def count; not_implemented end

  # @return [Enumerator]
  def each_count
    return enum_for(:each_count) unless block_given?

    count.times do
      yield single_item
    end
  end

  # @return [ __SELF__ ]
  def single_item; not_implemented end

  private def not_implemented
    raise NotImplementedError, "message"
  end
end

class SomeItemWhichIsABunch
  include MultipleItemBehaviour

  attr_reader :count
  def initialize(count)
    @count = count
  end

  def single_item
    self.class.new(1)
  end
end

SomeItemWhichIsABunch.each_count.take(5).map(&:something)

我知道这与OOP略有不同(最好将该项目拆分为一个容器和具体的项目),
但由于它是一堆相同的东西,并且已经存储在数据库中,因此我决定要返回这样的枚举器。


编辑2: 我将--embed-mixin选项传递给yard。 includer Class文档中的当前结果如下所示:(对不起,不同的模块名称) The details part of <code>Bar</code>

2 个答案:

答案 0 :(得分:1)

不幸的是,YARD无法做到这一点。最好的替代方法是在Foo#returns_new_self文档中明确说明。就个人而言,我会完全满意

module Foo
  ##
  # Returns a new instance of the object's class.
  #
  # @return [Object]
  def returns_new_self
    self.class.new
  end
end

class Bar
  include Foo
end

class Zap
  include Foo
end

产生以下文档:

foo documentation bar documentation

答案 1 :(得分:1)

yardoc不会按照您描述的方式生成文档。

生成文档时,BarZap的部分将显示:

  

Foo中包含的方法

     

#returns_new_self

#returns_new_self将链接到Foo的文档,而Foo的文档将说明该方法的可能返回类型。各个类将没有该方法的文档。

您仍然可以在returns_new_self内记录Foo。将返回类型设置为以下任何一种将被视为有效:

包含模块的类的值的硬编码列表:

# @return [Bar,Zap]

包含模块的类的超类:

# @return [Object]

literal void用于未定义的返回类型:

# @return [void]