I want to use metaprogramming to introduce docstring feature into Ruby language.
Here is very early prototype of the code I've written so far:
module Docstrings
def doc(docstring)
@docstrings ||= {}
if docstring.is_a? String
# Ruby 2.0 trick to get a caller of the method
method_caller = caller_locations(1,1)[0].label.to_sym
@docstrings[method_caller] ||= docstring
else
@docstrings[docstring]
end
end
end
# lets include it temporarily to see how it works
include Docstrings
class Method
include Docstrings
end
doc "Hello"
puts doc :"<main>" # => "Hello"
It works. But, sadly:
def square(x)
doc """This method returns square of x"""
x * x
end
doc(:square) # => nil
This is not working as I expected.
square(2)
doc(:square) # => """This method returns square of x"""
It will add docstring only when method square is invoked at least 1 time which is obvious.
My question is is it possible to implement in a way that a docstring will be attached more to a method, not to invocation of that method? I'm looking for hints not for solution, please tell me where should I look :)