我想使用元编程将docstring特性引入Ruby语言。
下面是我到目前为止编写的代码的早期原型:
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"它起作用了。但是,可悲的是:
def square(x)
doc """This method returns square of x"""
x * x
end
doc(:square) # => nil这不像我预料的那样有效。
square(2)
doc(:square) # => """This method returns square of x"""它只会在调用至少1次方法square时添加docstring,这是显而易见的。
我的问题是,是否有可能以一种将更多的docstring附加到方法,而不是调用该方法的方式实现?我在寻找提示而不是解决方案,请告诉我应该在哪里查找:)
发布于 2013-08-11 16:47:57
这似乎是可行的:(尽管,它并不是真正的元编程,只是一个黑客)。
假设你想要这个:
def add_these(a, b)
doc "This function adds two numbers"
a + b
end
whatsthedocdoc?(:add_these) # => "This function adds two numbers"
class Object
def whatsthedocdoc?(method)
meth = method(method.to_sym)
sours = meth.source
puts sours.lines.grep(/doc/).join.gsub(/doc|\"/, "").strip
end
end但这并不是那么简单。上面的片段假设方法是在main对象空间中定义的。让我们考虑一下这个例子:
class A
def add_these(a, b)
doc "This method adds two numbers."
end
end在本例中,whatsthedocdoc?方法中的代码应该更改为:
def whatsthedocdoc?(string)
receiver, meth = string.split(/\#/)
meth_instance = receiver.method(meth.to_sym)
sours = meth_instance.source
# rest is the same as above
end文档可以这样查看:
whatsthedocdoc?("A#add_these") # => This method adds two numbers.现在不太整洁了,是吗?
噢!还有另一种边缘情况:类方法
class A
def self.add_these(a, b)
doc "This too, adds two numbers"
end
end你知道这个主意..。
https://stackoverflow.com/questions/18173192
复制相似问题