给定以下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

如何以编程方式获取与特定对象(例如{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'))返回一个似乎是ast的实例,但我希望避免编写ast遍历器(yard必须具有此功能才能构造html文档,但我还没有找到它)。
(我正在使用院子v0.9.9,以防有用。)

最佳答案

所以,在玩了一点,并通过院子的来源,我可以理解院子是如何工作的。基本上,它会在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"

您应该能够使用它并根据需要转换为方法。
更多信息:https://github.com/lsegal/yard/blob/master/lib/yard/registry.rb#L225-L237

10-08 04:15