给定以下 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不断评论'}
)?
我希望 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 以防有帮助。)
最佳答案
所以在玩了一会儿并浏览了 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"
您应该能够使用它并根据需要将其转换为方法。
更多信息:https://github.com/lsegal/yard/blob/master/lib/yard/registry.rb#L225-L237
关于ruby - 以编程方式获取 Ruby 对象的 YARD 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45625765/