以编程方式获取 Ruby 对象的 YARD 注释

dug*_*dug 4 ruby yard

给定以下 ruby​​ 文件 foo.rb:

# this is a module comment
module A
  # this is a constant comment
  B = 'hi'
  # this is a class comment
  class C
    # this is a method comment
    # @param [String] name Who to say hi to
    # @return [String]
    def self.hi(name)
      "#{B}, #{name}"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

{A::C => 'this is a class comment'}如何以编程方式获取与特定对象(例如, )相关的注释{B => 'this is a constant comment'}

我期望YARD.parse(File.read('/path/to/foo.rb'))YARD::Parser::SourceParser.parse(File.read('/path/to/foo.rb'))做某事,但它们返回空数组。YARD::Parser::Ruby::RubyParser.parse(File.read('/path/to/foo.rb'))返回一个YARD::Parser::Ruby::RipperParser看似 AST 的实例,但我宁愿避免编写 AST 遍历器(YARD 必须具有此功能才能构建 HTML 文档,但我一直无法找到它)。

(我正在使用 YARD v0.9.9,以防有帮助。)

ave*_*ble 6

因此,在玩了一下并浏览了yard的来源之后,我可以理解yard是如何工作的。基本上,它创建了 后所有代码对象的注册表YARD.parse。我们可以这样访问它,

2.4.1 :033 > YARD.parse('./foo.rb')
=> []
2.4.1 :034 > YARD::Registry.all
=> [#<yardoc module A>, #<yardoc constant A::B>, #<yardoc class A::C>, #<yardoc method A::C.hi>]
2.4.1 :035 > code_objects = YARD::Registry.all.map {|object| {object.name => object.docstring} }.inject(&:merge)
{:A=>"this is a module comment", :B=>"this is a constant comment", :C=>"this is a class comment", :hi=>"this is a method comment"}
2.4.1 :036 > code_objects[:A]
=> "this is a module comment"
Run Code Online (Sandbox Code Playgroud)

您应该能够使用它并根据您的需要转换为方法。

更多信息:https://github.com/lsegal/yard/blob/master/lib/yard/registry.rb#L225-L237