oaklodge oaklodge - 3 months ago 15
Ruby Question

Parse Ruby file for comments

I want something that can parse a ruby file to give me the file positions of comments. Ranked by desirability:


  1. Ideally, there would be some command-line arg I could pass to "ruby" since of course "ruby" would know. But there doesn't seem to be one for this?

  2. Does anyone know if/where in "ruby" I could hook in and use its methods to know where the comments are?

  3. Some well-known regular expression?



Thanks!

Answer

Found: https://github.com/ruby/ruby/tree/trunk/ext/ripper

Example:

require 'ripper'
require 'pp'

class CommentRipper < Ripper::SexpBuilder
    def on_comment(token)
        super.tap { |result| pp result }
    end
end

contents = File.read("file.rb")
pp CommentRipper.new(contents).parse

Helped me understand Ripper better: http://svenfuchs.com/2009/7/5/using-ruby-1-9-ripper