Skip to content

Instantly share code, notes, and snippets.

@chendo
Created March 21, 2012 11:31
Show Gist options
  • Save chendo/2146319 to your computer and use it in GitHub Desktop.
Save chendo/2146319 to your computer and use it in GitHub Desktop.
Python-like docstrings in Ruby!
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
@chendo
Copy link
Author

chendo commented Dec 28, 2012

See http://eval.in/5449 for the output of this script.

@coderhs
Copy link

coderhs commented Sep 14, 2013

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.

@bfontaine
Copy link

@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.

@chendo
Copy link
Author

chendo commented Aug 8, 2018

@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