views:

163

answers:

2

Is there a way for programmatically accessing a method comments? or an attribute comments?

I would like to use it as a description for the method in a documentation which I don't want to be static or generated with rdoc or equivalent.

Here is an example of a Ruby class:

Class MyClass
  ##
  # This method tries over and over until it is tired
  def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try
    puts thing_to_try
    go_go_go thing_to_try, tries - 1
  end
end

Basically, I'd like to be able to do the following:

get_comment MyClass.gogogo # => This method tries over and over until it is tired
+1  A: 

Comments are (usually) thrown away by the lexer and are not available in the symbol tables to Ruby at execution time.

I think the closest that you could do is to either

(a) Implement get_comment in such a way that it creates a regex on the fly and searches the source file for a match. You'd need to change your syntax like this ...

 get_comment :MyClass, :go_go_go

You would convert the symbols to strings, assume that the source file is myclass.rb and search therein for a match on the comment-def-method_name pattern.

(b) Have a method called from every source file which built a global comment table.

Regardless, it's messy and more hassle than it's worth.

Chris McCauley
Makes sense. I assume I'm going to change my mind and reconsider my needs. Thanks
Arnaud Leymet
+2  A: 
Jörg W Mittag
That was hell of a well written answer I must admit. Thank you for your insights on this. You've made my mind: I'll never do something as hacky as this for my app.
Arnaud Leymet