LoginSignup
6
4

More than 5 years have passed since last update.

Ruby のソースコードからコメントを集める gem を作った

Posted at

Ruby のソースコードからコメントを集める comment_collector という gem を作りました。

例えば、こんな感じのコードがある時に

example.rb
# class comment
# this is sample
class Foo
  BAR = 'hello' # string

  # method
  def say
    'hi'
  end
end

=begin
multi line
comments
=end

こんな感じでコードを書くと

comment.rb
require 'comment_collector'

comments = CommentCollector.get(File.read('example.rb'))

puts '=' * 20

comments.each do |comment|
  puts comment.value
  puts '=' * 20
end

こんな感じでコメントだけを抜き出してくれます。

$ ruby comment.rb
====================
# class comment
# this is sample
====================
# string
====================
# method
====================
=begin
multi line
comments
=end
====================

CommentCollector.get では Comment の配列が返ってきます。Comment は構造体で定義していて、以下のような感じの情報が取れるようになってます。

Comment = Struct.new(:value, :first_lineno, :first_column, :last_lineno, :last_column)

仕組み

Ruby の静的解析ツールを使ってていつも「コメント部分が取れないな」と思っていたのですが、逆に「ソースコードからパースした結果を取り除いたらコメント部分が残るのでは」と思い書いてみた次第です。実際には __END__ とか残ったりしたのですが、そこら辺は無理やり処理しました。

最初は RubyVM::AST を使っていたのですが、あまり意図しないパース結果になったりしたので途中で parser gem に切り替えて実装しました。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4