以编程方式获取 Ruby 个对象的 YARD 评论
Get YARD comments for Ruby objects programmatically
给定以下 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'))
能做点什么,但它们 return 是空数组。 YARD::Parser::Ruby::RubyParser.parse(File.read('/path/to/foo.rb'))
return 一个 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 文件,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'))
能做点什么,但它们 return 是空数组。 YARD::Parser::Ruby::RubyParser.parse(File.read('/path/to/foo.rb'))
return 一个 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