Created
March 21, 2012 11:31
-
-
Save chendo/2146319 to your computer and use it in GitHub Desktop.
Python-like docstrings in Ruby!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DocStrings | |
def docstrings! | |
""" | |
This is a docstring that's syntactically valid! | |
It'll do multiple lines! | |
""" | |
end | |
def single_line_docstring | |
"""Single line docstring!""" | |
end | |
def why? | |
""" | |
Cause I can? Duh. | |
""" | |
end | |
def how_does_it_work? | |
""" | |
I learnt that two strings side by side concats them together | |
and is valid Ruby from Peter Cooper (@peterc)'s Ruby Trick Shots found | |
at http://rubyreloaded.com/trickshots/ | |
Then the rest is just some good ol' regex. | |
""" | |
end | |
def notes | |
""" | |
Double quotes not together like this: "" | |
breaks it. | |
Requires Method#source_location | |
Code below is unoptimised and needs further work | |
""" | |
end | |
def no_docstring | |
end | |
end | |
class Method | |
def doc | |
@doc ||= begin | |
path, line_number = source_location | |
return nil unless path && File.exists?(path) | |
file = File.read(path) | |
if file =~ Regexp.new(%Q{\\A(?:.*?\n){#{line_number}}\s*?"""([\\s\\S]+?)"""}) | |
$1.gsub(/\n\s+/, "\n").strip | |
else | |
nil | |
end | |
end | |
end | |
end | |
doc = DocStrings.new | |
(doc.methods - methods).each do |method_name| | |
puts "method name #{method_name.to_s}:" | |
puts doc.method(method_name).doc | |
puts "----" | |
end |
Writing these Doc string as you mentioned in ruby, won't the interpreter process them when you execute the code. Won't it be better, if you use the comment tag to write the documentation and then parse them using YARD.
@coderhs the problem of writing documentation in comments is that it’s not accessible from the code / the interpreter.
In Python, you have access to a class/function’s documentation with obj.__doc__
, or help(obj)
. This is really helpful when you’re in the interpreter and/or have no access to Internet.
@coderhs: YARV will detect that the string is not being used and not generate the bytecode for it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://eval.in/5449 for the output of this script.