banister / method_source

return the sourcecode for a method
MIT License
361 stars 43 forks source link

Incorrect Comment Parsing for Methods #83

Open a-chacon opened 4 months ago

a-chacon commented 4 months ago

When using the method_source gem to retrieve comments associated with instance methods, it appears that the comments from preceding methods are also included. This results in incorrect comment retrieval, especially when there are multiple methods with comments in between. I made a little script to show it:

require 'method_source'

class StringTransformer
  def initialize(str)
    @str = str
  end

  # Reverse the string
  def reverse_string
    @str.reverse
  end

  # Convert the string to uppercase
  # TODO: Implement this method
  # def uppercase_string
  # end

  # Replace spaces with underscores
  def replace_spaces
    @str.gsub(' ', '_')
  end
end

StringTransformer.instance_method(:reverse_string).comment.display
# =>  # Reverse the string
StringTransformer.instance_method(:replace_spaces).comment.display
# =>  # Convert the string to uppercase
#     # TODO Implement this method
#     # def uppercase_string
#     # end
#     # Replace spaces with underscores

I format It with a default Rubocop configuration.

I think the expected behavior should be:

StringTransformer.instance_method(:reverse_string).comment.display
# => # Reverse the string
StringTransformer.instance_method(:replace_spaces).comment.display
# => # Replace spaces with underscores

I looked into the major documentation tools in Ruby (YARD and RDoc) and none support parsing block comments separated by a whitespace (though I am not 100% sure). However, I think the comment before the method should be extracted until the next whitespace and not more.